source: trunk/src/series/civ_series.m @ 637

Last change on this file since 637 was 637, checked in by sommeria, 11 years ago

civ_series cleaned. Introduction of a nc file as input (to further debug)

File size: 46.1 KB
Line 
1%'civ_series': PIV function activated by the general GUI series
2% --- call the sub-functions:
3%   civ: PIV function itself
4%   fix: removes false vectors after detection by various criteria
5%   filter_tps: make interpolation-smoothing
6%------------------------------------------------------------------------
7% function [Data,errormsg,result_conv]= civ_series(Param,ncfile)
8%
9%OUTPUT
10% Data=structure containing the PIV results and information on the processing parameters
11% errormsg=error message char string, default=''
12% resul_conv: image inter-correlation function for the last grid point (used for tests)
13%
14%INPUT:
15% Param: input images and processing parameters
16%     .Civ1: for civ1
17%     .Fix1:
18%     .Patch1:
19%     .Civ2: for civ2
20%     .Fix2:
21%     .Patch2:
22% ncfile: name of a netcdf file to be created for the result (extension .nc)
23%
24%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
25%  Copyright  2011, LEGI / CNRS-UJF-INPG, joel.sommeria@legi.grenoble-inp.fr.
26%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
27%     This is part of the toolbox UVMAT.
28%
29%     UVMAT is free software; you can redistribute it and/or modify
30%     it under the terms of the GNU General Public License as published by
31%     the Free Software Foundation; either version 2 of the License, or
32%     (at your option) any later version.
33%
34%     UVMAT is distributed in the hope that it will be useful,
35%     but WITHOUT ANY WARRANTY; without even the implied warranty of
36%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
37%     GNU General Public License (open UVMAT/COPYING.txt) for more details.
38%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
39
40function [Data,errormsg,result_conv]= civ_series(Param,ncfile)
41errormsg='';
42path_series=fileparts(which('series'));
43addpath(fullfile(path_series,'series'))
44%% set the input elements needed on the GUI series when the action is selected in the menu ActionName or InputTable refreshed
45if isstruct(Param) && isequal(Param.Action.RUN,0)
46    Data=civ_input(Param);% introduce the civ parameters using the GUI civ_input
47    Data.Program=mfilename;%gives the name of the current function
48    Data.AllowInputSort='off';% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
49    Data.WholeIndexRange='off';% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
50    Data.NbSlice='off'; %nbre of slices ('off' by default)
51    Data.VelType='off';% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
52    Data.FieldName='off';% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
53    Data.FieldTransform = 'off';%can use a transform function
54    Data.ProjObject='off';%can use projection object(option 'off'/'on',
55    Data.Mask='off';%can use mask option   (option 'off'/'on', 'off' by default)
56    Data.OutputDirExt='.civ';%set the output dir extension
57    filecell=get_file_series(Param);%check existence of the first input file
58    if ~exist(filecell{1,1},'file')
59        msgbox_uvmat('WARNING','the first input file does not exist')
60    else
61        FileType=get_file_type(filecell{1,1});
62        if isempty(find(strcmp(FileType,{'civdata','image','multimage','mmreader','video'})));% =1 for images
63            msgbox_uvmat('ERROR',['bad input file type for ' mfilename ': an image or civdata file is needed'])
64        end
65    end
66    return
67end
68
69%% read input parameters from an xml file if input is a file name (batch mode)
70checkrun=1;
71if ischar(Param)
72    Param=xml2struct(Param);% read Param as input file (batch case)
73    checkrun=0;
74end
75hseries=findobj(allchild(0),'Tag','series');
76RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
77WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
78
79%% input files and indexing
80NbField=1;
81MaxIndex_i=Param.IndexRange.MaxIndex_i;
82MinIndex_i=Param.IndexRange.MinIndex_i;
83MaxIndex_j=1;MinIndex_j=1;
84if isfield(Param.IndexRange,'MaxIndex_j')&& isfield(Param.IndexRange,'MinIndex_j')
85    MaxIndex_j=Param.IndexRange.MaxIndex_j;
86    MinIndex_j=Param.IndexRange.MinIndex_j;
87end
88if isfield(Param,'InputTable')
89    [filecell,i_series,tild,j_series]=get_file_series(Param);
90    if ~exist(filecell{1,1},'file')
91        displ('ERROR: the first input file does not exist')
92        return
93    else
94        FileType=get_file_type(filecell{1,1});
95        iview_nc=0;
96        iview_A=0;
97        iview_B=0;
98        switch FileType
99            case 'civdata';% =1 for images
100                iview_nc=1;
101                if size(filecell,1)>=2
102                    iview_A=2;iview_B=2;
103                    if size(filecell,1)>=3
104                        iview_B=3;
105                    end
106                end
107            case {'image','multimage','mmreader','video'}
108                iview_A=1;
109                if size(filecell,1)>=2
110                    iview_B=2;
111                end
112        end
113    end
114    if iview_A~=0
115        [FileType_A,FileInfo_A,VideoObject_A]=get_file_type(filecell{1,1});
116        if isempty(strcmp(FileType_A,{'multimage','mmreader','video'}))
117            displ(['ERROR: the file line ' num2str(iview_A) ' must be an image'])
118        end
119        RootPath=Param.InputTable{1,1};
120        RootFile=Param.InputTable{1,3};
121        SubDir=Param.InputTable{1,2};
122        NomType=Param.InputTable{1,4};
123        FileExt=Param.InputTable{1,5};
124    end
125    if iview_B==0
126        FileType_B=FileType_A;
127        VideoObject_B=VideoObject_A;
128        PairCiv1=Param.ActionInput.PairIndices.ListPairCiv1;
129        PairCiv2='';
130        if isfield(Param.ActionInput.PairIndices,'ListPairCiv2')
131            PairCiv2=Param.ActionInput.PairIndices.ListPairCiv2;
132        end
133        [i1_series_Civ1,i2_series_Civ1,j1_series_Civ1,j2_series_Civ1,check_bounds,NomTypeNc]=...
134            find_pair_indices(PairCiv1,i_series{1},j_series{1},MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j);
135        if ~isempty(PairCiv2)
136            [i1_series_Civ2,i2_series_Civ2,j1_series_Civ2,j2_series_Civ2,check_bounds_Civ2]=...
137                find_pair_indices(PairCiv2,i_series{1},j_series{1},MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j);
138            check_bounds=check_bounds | check_bounds_Civ2;
139        end
140        i1_series_Civ1=i1_series_Civ1(~check_bounds);
141        i2_series_Civ1=i2_series_Civ1(~check_bounds);
142        j1_series_Civ1=j1_series_Civ1(~check_bounds);
143        j2_series_Civ1=j2_series_Civ1(~check_bounds);
144        if isempty(j_series{1})
145            FrameIndex_A_Civ1=i1_series_Civ1;
146            FrameIndex_B_Civ1=i2_series_Civ1;
147        else
148            FrameIndex_A_Civ1=j1_series_Civ1;
149            FrameIndex_B_Civ1=j2_series_Civ1;
150        end
151        if ~isempty(PairCiv2)
152            i1_series_Civ2=i1_series_Civ2(~check_bounds);
153            i2_series_Civ2=i2_series_Civ2(~check_bounds);
154            j1_series_Civ2=j1_series_Civ2(~check_bounds);
155            j2_series_Civ2=j2_series_Civ2(~check_bounds);
156            if isempty(j_series{1})
157                FrameIndex_A_Civ2=i1_series_Civ2;
158                FrameIndex_B_Civ2=i2_series_Civ2;
159            else
160                FrameIndex_A_Civ2=j1_series_Civ2;
161                FrameIndex_B_Civ2=j2_series_Civ2;
162            end
163        end
164    else
165        [FileType_B,FileInfo,VideoObject_B]=get_file_type(filecell{2,1});
166        if isempty(find(strcmp(FileType_B,{'multimage','mmreader','video'})))
167            displ(['ERROR: the file line ' num2str(iview_B) ' must be an image'])
168        end
169        %TODO : introduce the second file series if relevant: case %displacement
170    end
171end
172NbField=numel(i1_series_Civ1);
173
174%% Output directory
175OutputDir=[Param.OutputSubDir Param.OutputDirExt];
176
177Data.ListGlobalAttribute={'Conventions','Program','CivStage'};
178Data.Conventions='uvmat/civdata';% states the conventions used for the description of field variables and attributes
179Data.Program='civ_series';
180Data.CivStage=0;%default
181ListVarCiv1={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F'}; %variables to read
182ListVarFix1={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F','Civ1_FF'};
183mask='';
184maskname='';%default
185check_civx=0;%default
186check_civ1=0;%default
187check_patch1=0;%default
188
189%% get timing from the ImaDoc file or input video
190XmlFileName=find_imadoc(RootPath,SubDir,RootFile,FileExt);
191time=[];
192if ~isempty(XmlFileName)
193    XmlData=imadoc2struct(XmlFileName);
194        if isfield(XmlData,'Time')
195            time=XmlData.Time;
196            TimeSource='xml';
197        end
198        if isfield(XmlData,'Camera')
199            if isfield(XmlData.Camera,'NbSlice')&& ~isempty(XmlData.Camera.NbSlice)
200                NbSlice_calib{iview}=XmlData.Camera.NbSlice;% Nbre of slices for Zindex in phys transform
201                if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
202                    msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
203                end
204            end
205            if isfield(XmlData.Camera,'TimeUnit')&& ~isempty(XmlData.Camera.TimeUnit)
206                TimeUnit=XmlData.Camera.TimeUnit;
207            end
208        end
209end
210if isempty(time) && ~isempty(find(strcmp(FileType_A,{'mmreader','video'})))% case of video input
211    time=zeros(2,FileInfo_A.NumberOfFrames+1);
212    time(2,:)=(0:1/FileInfo_A.FrameRate:(FileInfo_A.NumberOfFrames)/FileInfo_A.FrameRate);
213    TimeSource='video';
214    % set(han:dles.Dt_txt,'String',['Dt=' num2str(1000/imainfo.FrameRate) 'ms']);%display the elementary time interval in millisec
215    ColorType='truecolor';
216end
217if isempty(time)% time = index i +0.001 index j by default
218    time=(MinIndex_i:MaxIndex_i)'*ones(1,MaxIndex_j-MinIndex_j+1);
219    time=time+0.001*ones(MaxIndex_i-MinIndex_i+1,1)*(MinIndex_j:MaxIndex_j);
220    time=[zeros(1,MaxIndex_j-MinIndex_j+1);time];% insert a first line of zeros
221    time=[zeros(MaxIndex_i-MinIndex_i+2,1) time];% insert a first column of zeros
222end
223   
224if length(FileInfo_A) >1 %case of image with multiple frames
225    nbfield=length(FileInfo_A);
226    nbfield_j=1;
227end
228
229%%%%% MAIN LOOP %%%%%%
230for ifield=1:NbField
231    update_waitbar(WaitbarHandle,ifield/NbField)
232    if ~isempty(RUNHandle) && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
233        disp('program stopped by user')
234        break
235    end
236    %% Civ1
237    if isfield (Param.ActionInput,'Civ1')
238        par_civ1=Param.ActionInput.Civ1;
239        if isfield(par_civ1,'reverse_pair')% A REVOIR
240            if par_civ1.reverse_pair
241                if ischar(par_civ1.ImageB)
242                    temp=par_civ1.ImageA;
243                    par_civ1.ImageA=imread(par_civ1.ImageB);
244                end
245                if ischar(temp)
246                    par_civ1.ImageB=imread(temp);
247                end
248            end
249        else
250            ImageName_A=fullfile_uvmat(RootPath,SubDir,RootFile,FileExt,NomType,i1_series_Civ1(ifield),[],j1_series_Civ1(ifield));
251            [par_civ1.ImageA,VideoObject_A] = read_image(ImageName_A,FileType_A,VideoObject_A,FrameIndex_A_Civ1(ifield));
252            ImageName_B=fullfile_uvmat(RootPath,SubDir,RootFile,FileExt,NomType,i2_series_Civ1(ifield),[],j2_series_Civ1(ifield));
253            [par_civ1.ImageB,VideoObject_B] = read_image(ImageName_B,FileType_B,VideoObject_B,FrameIndex_B_Civ1(ifield));
254        end
255        ncfile=fullfile_uvmat(RootPath,OutputDir,RootFile,'.nc',NomTypeNc,i1_series_Civ1(ifield),i2_series_Civ1(ifield),...
256            j1_series_Civ1(ifield),j2_series_Civ1(ifield));
257        par_civ1.ImageWidth=FileInfo_A.Width;
258        par_civ1.ImageHeight=FileInfo_A.Height;
259        list_param=(fieldnames(Param.ActionInput.Civ1))';
260        Civ1_param=regexprep(list_param,'^.+','Civ1_$0');% insert 'Civ1_' before  each string in list_param
261        Civ1_param=[{'Civ1_ImageA','Civ1_ImageB','Civ1_Time','Civ1_Dt'} Civ1_param]; %insert the names of the two input images
262        %indicate the values of all the global attributes in the output data
263        Data.Civ1_ImageA=ImageName_A;
264        Data.Civ1_ImageB=ImageName_B;
265        i1=i1_series_Civ1(ifield);
266        i2=i1;
267        if ~isempty(i2_series_Civ1)
268            i2=i2_series_Civ1(ifield);
269        end
270        j1=1;
271        if ~isempty(j1_series_Civ1)
272            j1=j1_series_Civ1(ifield);
273        end
274        j2=j1;
275        if ~isempty(j2_series_Civ1)
276            j2=j2_series_Civ1(ifield);
277        end
278        Data.Civ1_Time=(time(i2+1,j2+1)+time(i1+1,j1+1))/2;
279        Data.Civ1_Dt=time(i2+1,j2+1)-time(i1+1,j1+1);
280        for ilist=1:length(list_param)
281            Data.(Civ1_param{4+ilist})=Param.ActionInput.Civ1.(list_param{ilist});
282        end
283        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ1_param];
284        Data.CivStage=1;
285       
286        % set the list of variables
287        Data.ListVarName={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_F','Civ1_C'};%  cell array containing the names of the fields to record
288        Data.VarDimName={'nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1'};
289        Data.VarAttribute{1}.Role='coord_x';
290        Data.VarAttribute{2}.Role='coord_y';
291        Data.VarAttribute{3}.Role='vector_x';
292        Data.VarAttribute{4}.Role='vector_y';
293        Data.VarAttribute{5}.Role='warnflag';
294       
295        if strcmp(Param.ActionInput.ListCompareMode, 'PIV volume')
296            Data.ListVarName=[Data.ListVarName 'Civ1_Z'];
297            Data.Civ1_X=[];Data.Civ1_Y=[];Data.Civ1_Z=[];
298            Data.Civ1_U=[];Data.Civ1_V=[];Data.Civ1_C=[];Data.Civ1_F=[];
299            for ivol=1:NbSlice
300                % caluclate velocity data (y and v in indices, reverse to y component)
301                [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ1);
302                if ~isempty(errormsg)
303                    return
304                end
305                Data.Civ1_X=[Data.Civ1_X reshape(xtable,[],1)];
306                Data.Civ1_Y=[Data.Civ1_Y reshape(Param.Civ1.ImageHeight-ytable+1,[],1)];
307                Data.Civ1_Z=[Data.Civ1_Z ivol*ones(numel(xtable),1)];% z=image index in image coordinates
308                Data.Civ1_U=[Data.Civ1_U reshape(utable,[],1)];
309                Data.Civ1_V=[Data.Civ1_V reshape(-vtable,[],1)];
310                Data.Civ1_C=[Data.Civ1_C reshape(ctable,[],1)];
311                Data.Civ1_F=[Data.Civ1_C reshape(F,[],1)];
312            end
313        else %usual PIV
314            % caluclate velocity data (y and v in indices, reverse to y component)
315            [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ1);
316            if ~isempty(errormsg)
317                return
318            end
319            Data.Civ1_X=reshape(xtable,[],1);
320            Data.Civ1_Y=reshape(par_civ1.ImageHeight-ytable+1,[],1);
321            Data.Civ1_U=reshape(utable,[],1);
322            Data.Civ1_V=reshape(-vtable,[],1);
323            Data.Civ1_C=reshape(ctable,[],1);
324            Data.Civ1_F=reshape(F,[],1);
325        end
326    else
327        if exist('ncfile','var')
328            CivFile=ncfile;
329        elseif isfield(Param.Patch1,'CivFile')
330            CivFile=Param.Patch1.CivFile;
331        end
332        Data=nc2struct(CivFile,'ListGlobalAttribute','absolut_time_T0'); %look for the constant 'absolut_time_T0' to detect old civx data format
333        if isfield(Data,'Txt')
334            errormsg=Data.Txt;
335            return
336        end
337        if ~isempty(Data.absolut_time_T0')%read civx file
338            check_civx=1;% test for old civx data format
339            [Data,vardetect,ichoice]=nc2struct(CivFile);%read the variables in the netcdf file
340        else
341            Data=nc2struct(CivFile);%read civ1 and fix1 data in the existing netcdf file
342        end
343    end
344   
345    %% Fix1
346    if isfield (Param.ActionInput,'Fix1')
347        ListFixParam=fieldnames(Param.ActionInput.Fix1);
348        for ilist=1:length(ListFixParam)
349            ParamName=ListFixParam{ilist};
350            ListName=['Fix1_' ParamName];
351            eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
352            eval(['Data.' ListName '=Param.ActionInput.Fix1.' ParamName ';'])
353        end
354        if check_civx
355            if ~isfield(Data,'fix')
356                Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix'];
357                Data.fix=1;
358                Data.ListVarName=[Data.ListVarName {'vec_FixFlag'}];
359                Data.VarDimName=[Data.VarDimName {'nb_vectors'}];
360            end
361            Data.vec_FixFlag=fix(Param.ActionInput.Fix1,Data.vec_F,Data.vec_C,Data.vec_U,Data.vec_V,Data.vec_X,Data.vec_Y);
362        else
363            Data.ListVarName=[Data.ListVarName {'Civ1_FF'}];
364            Data.VarDimName=[Data.VarDimName {'nb_vec_1'}];
365            nbvar=length(Data.ListVarName);
366            Data.VarAttribute{nbvar}.Role='errorflag';
367            Data.Civ1_FF=fix(Param.ActionInput.Fix1,Data.Civ1_F,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V);
368            Data.CivStage=2;
369        end
370    end
371    %% Patch1
372    if isfield (Param.ActionInput,'Patch1')
373        if check_civx
374            errormsg='Civ Matlab input needed for patch';
375            return
376        end
377       
378        Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch1_Rho','Patch1_Threshold','Patch1_SubDomain'}];
379        Data.Patch1_FieldSmooth=Param.ActionInput.Patch1.FieldSmooth;
380        Data.Patch1_MaxDiff=Param.ActionInput.Patch1.MaxDiff;
381        Data.Patch1_SubDomainSize=Param.ActionInput.Patch1.SubDomainSize;
382        nbvar=length(Data.ListVarName);
383        Data.ListVarName=[Data.ListVarName {'Civ1_U_smooth','Civ1_V_smooth','Civ1_SubRange','Civ1_NbCentres','Civ1_Coord_tps','Civ1_U_tps','Civ1_V_tps'}];
384        Data.VarDimName=[Data.VarDimName {'nb_vec_1','nb_vec_1',{'nb_coord','nb_bounds','nb_subdomain_1'},'nb_subdomain_1',...
385            {'nb_tps_1','nb_coord','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'}}];
386        Data.VarAttribute{nbvar+1}.Role='vector_x';
387        Data.VarAttribute{nbvar+2}.Role='vector_y';
388        Data.VarAttribute{nbvar+5}.Role='coord_tps';
389        Data.VarAttribute{nbvar+6}.Role='vector_x';
390        Data.VarAttribute{nbvar+7}.Role='vector_y';
391        Data.Civ1_U_smooth=zeros(size(Data.Civ1_X));
392        Data.Civ1_V_smooth=zeros(size(Data.Civ1_X));
393        if isfield(Data,'Civ1_FF')
394            ind_good=find(Data.Civ1_FF==0);
395        else
396            ind_good=1:numel(Data.Civ1_X);
397        end
398        [Data.Civ1_SubRange,Data.Civ1_NbCentres,Data.Civ1_Coord_tps,Data.Civ1_U_tps,Data.Civ1_V_tps,tild,Ures, Vres,tild,FFres]=...
399            filter_tps([Data.Civ1_X(ind_good) Data.Civ1_Y(ind_good)],Data.Civ1_U(ind_good),Data.Civ1_V(ind_good),[],Data.Patch1_SubDomainSize,Data.Patch1_FieldSmooth,Data.Patch1_MaxDiff);
400        Data.Civ1_U_smooth(ind_good)=Ures;
401        Data.Civ1_V_smooth(ind_good)=Vres;
402        Data.Civ1_FF(ind_good)=FFres;
403        Data.CivStage=3;
404    end
405   
406    %% Civ2
407    if isfield (Param.ActionInput,'Civ2')
408        par_civ2=Param.ActionInput.Civ2;
409        par_civ2.ImageA=[];
410        par_civ2.ImageB=[];
411        %         if ~isfield(Param.Civ1,'ImageA')
412        ImageName_A_Civ2=fullfile_uvmat(RootPath,SubDir,RootFile,FileExt,NomType,i1_series_Civ2(ifield),[],j1_series_Civ2(ifield));
413
414        if strcmp(ImageName_A_Civ2,ImageName_A) && isequal(FrameIndex_A_Civ1(ifield),FrameIndex_A_Civ2(ifield))
415            par_civ2.ImageA=par_civ1.ImageA;
416        else
417            [par_civ2.ImageA,VideoObject_A] = read_image(ImageName_A,FileType_A,VideoObject_A,FrameIndex_A_Civ2(ifield));
418        end
419        ImageName_B_Civ2=fullfile_uvmat(RootPath,SubDir,RootFile,FileExt,NomType,i2_series_Civ2(ifield),[],j2_series_Civ2(ifield));
420        if strcmp(ImageName_B_Civ2,ImageName_B) && isequal(FrameIndex_B_Civ1(ifield),FrameIndex_B_Civ2)
421            par_civ2.ImageB=par_civ1.ImageB;
422        else
423            [par_civ2.ImageB,VideoObject_B] = read_image(ImageName_B,FileType_B,VideoObject_B,FrameIndex_B_Civ2(ifield));
424        end     
425       
426        ncfile=fullfile_uvmat(RootPath,OutputDir,RootFile,'.nc',NomTypeNc,i1_series_Civ2(ifield),i2_series_Civ2(ifield),...
427            j1_series_Civ2(ifield),j2_series_Civ2(ifield));
428        par_civ2.ImageWidth=FileInfo_A.Width;
429        par_civ2.ImageHeight=FileInfo_A.Height;
430       
431        if isfield(par_civ2,'Grid')% grid points set as input file
432            if ischar(par_civ2.Grid)%read the grid file if the input is a file name
433                par_civ2.Grid=dlmread(par_civ2.Grid);
434                par_civ2.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
435            end
436        else% automatic grid
437            minix=floor(par_civ2.Dx/2)-0.5;
438            maxix=minix+par_civ2.Dx*floor((par_civ2.ImageWidth-1)/par_civ2.Dx);
439            miniy=floor(par_civ2.Dy/2)-0.5;
440            maxiy=minix+par_civ2.Dy*floor((par_civ2.ImageHeight-1)/par_civ2.Dy);
441            [GridX,GridY]=meshgrid(minix:par_civ2.Dx:maxix,miniy:par_civ2.Dy:maxiy);
442            par_civ2.Grid(:,1)=reshape(GridX,[],1);
443            par_civ2.Grid(:,2)=reshape(GridY,[],1);
444        end
445        Shiftx=zeros(size(par_civ2.Grid,1),1);% shift expected from civ1 data
446        Shifty=zeros(size(par_civ2.Grid,1),1);
447        nbval=zeros(size(par_civ2.Grid,1),1);
448        if par_civ2.CheckDeformation
449            DUDX=zeros(size(par_civ2.Grid,1),1);
450            DUDY=zeros(size(par_civ2.Grid,1),1);
451            DVDX=zeros(size(par_civ2.Grid,1),1);
452            DVDY=zeros(size(par_civ2.Grid,1),1);
453        end
454        NbSubDomain=size(Data.Civ1_SubRange,3);
455        % get the guess from patch1
456        for isub=1:NbSubDomain
457            nbvec_sub=Data.Civ1_NbCentres(isub);
458            ind_sel=find(GridX>=Data.Civ1_SubRange(1,1,isub) & GridX<=Data.Civ1_SubRange(1,2,isub) & GridY>=Data.Civ1_SubRange(2,1,isub) & GridY<=Data.Civ1_SubRange(2,2,isub));
459            epoints = [GridX(ind_sel) GridY(ind_sel)];% coordinates of interpolation sites
460            ctrs=Data.Civ1_Coord_tps(1:nbvec_sub,:,isub) ;%(=initial points) ctrs
461            nbval(ind_sel)=nbval(ind_sel)+1;% records the number of values for eacn interpolation point (in case of subdomain overlap)
462            EM = tps_eval(epoints,ctrs);
463            Shiftx(ind_sel)=Shiftx(ind_sel)+EM*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
464            Shifty(ind_sel)=Shifty(ind_sel)+EM*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
465            if par_civ2.CheckDeformation
466                [EMDX,EMDY] = tps_eval_dxy(epoints,ctrs);%2D matrix of distances between extrapolation points epoints and spline centres (=site points) ctrs
467                DUDX(ind_sel)=DUDX(ind_sel)+EMDX*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
468                DUDY(ind_sel)=DUDY(ind_sel)+EMDY*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
469                DVDX(ind_sel)=DVDX(ind_sel)+EMDX*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
470                DVDY(ind_sel)=DVDY(ind_sel)+EMDY*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
471            end
472        end
473        mask='';
474        if par_civ2.CheckMask&&~isempty(par_civ2.Mask)&& ~strcmp(maskname,par_civ2.Mask)% mask exist, not already read in civ1
475            mask=imread(par_civ2.Mask);
476        end
477        ibx2=ceil(par_civ2.CorrBoxSize(1)/2);
478        iby2=ceil(par_civ2.CorrBoxSize(2)/2);
479        par_civ2.SearchBoxSize(1)=2*ibx2+9;% search ara +-4 pixels around the guess
480        par_civ2.SearchBoxSize(2)=2*iby2+9;
481        par_civ2.SearchBoxShift=[Shiftx(nbval>=1)./nbval(nbval>=1) Shifty(nbval>=1)./nbval(nbval>=1)];
482        par_civ2.Grid=[GridX(nbval>=1)-par_civ2.SearchBoxShift(:,1)/2 GridY(nbval>=1)-par_civ2.SearchBoxShift(:,2)/2];% grid taken at the extrapolated origin of the displacement vectors
483        if par_civ2.CheckDeformation
484            par_civ2.DUDX=DUDX./nbval;
485            par_civ2.DUDY=DUDY./nbval;
486            par_civ2.DVDX=DVDX./nbval;
487            par_civ2.DVDY=DVDY./nbval;
488        end
489        % caluclate velocity data (y and v in indices, reverse to y component)
490        [xtable ytable utable vtable ctable F] = civ (par_civ2);
491
492        list_param=(fieldnames(Param.ActionInput.Civ2))';
493        Civ2_param=regexprep(list_param,'^.+','Civ2_$0');% insert 'Civ2_' before  each string in list_param
494        Civ2_param=[{'Civ2_ImageA','Civ2_ImageB','Civ2_Time','Civ2_Dt'} Civ2_param]; %insert the names of the two input images
495        %indicate the values of all the global attributes in the output data
496        Data.Civ2_ImageA=ImageName_A;
497        Data.Civ2_ImageB=ImageName_B;
498        Data.Civ2_Time=1;
499        Data.Civ2_Dt=1;
500        for ilist=1:length(list_param)
501            Data.(Civ2_param{4+ilist})=Param.ActionInput.Civ2.(list_param{ilist});
502        end
503        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ2_param];
504       
505        nbvar=numel(Data.ListVarName);
506        Data.ListVarName=[Data.ListVarName {'Civ2_X','Civ2_Y','Civ2_U','Civ2_V','Civ2_F','Civ2_C'}];%  cell array containing the names of the fields to record
507        Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2'}];
508        Data.VarAttribute{nbvar+1}.Role='coord_x';
509        Data.VarAttribute{nbvar+2}.Role='coord_y';
510        Data.VarAttribute{nbvar+3}.Role='vector_x';
511        Data.VarAttribute{nbvar+4}.Role='vector_y';
512        Data.VarAttribute{nbvar+5}.Role='warnflag';
513        Data.Civ2_X=reshape(xtable,[],1);
514        Data.Civ2_Y=reshape(size(par_civ2.ImageA,1)-ytable+1,[],1);
515        Data.Civ2_U=reshape(utable,[],1);
516        Data.Civ2_V=reshape(-vtable,[],1);
517        Data.Civ2_C=reshape(ctable,[],1);
518        Data.Civ2_F=reshape(F,[],1);
519        Data.CivStage=Data.CivStage+1;
520    end
521   
522    %% Fix2
523    if isfield (Param.ActionInput,'Fix2')
524        ListFixParam=fieldnames(Param.ActionInput.Fix2);
525        for ilist=1:length(ListFixParam)
526            ParamName=ListFixParam{ilist};
527            ListName=['Fix2_' ParamName];
528            eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
529            eval(['Data.' ListName '=Param.ActionInput.Fix2.' ParamName ';'])
530        end
531        if check_civx
532            if ~isfield(Data,'fix2')
533                Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix2'];
534                Data.fix2=1;
535                Data.ListVarName=[Data.ListVarName {'vec2_FixFlag'}];
536                Data.VarDimName=[Data.VarDimName {'nb_vectors2'}];
537            end
538            Data.vec_FixFlag=fix(Param.Fix2,Data.vec2_F,Data.vec2_C,Data.vec2_U,Data.vec2_V,Data.vec2_X,Data.vec2_Y);
539        else
540            Data.ListVarName=[Data.ListVarName {'Civ2_FF'}];
541            Data.VarDimName=[Data.VarDimName {'nb_vec_2'}];
542            nbvar=length(Data.ListVarName);
543            Data.VarAttribute{nbvar}.Role='errorflag';
544            Data.Civ2_FF=fix(Param.ActionInput.Fix2,Data.Civ2_F,Data.Civ2_C,Data.Civ2_U,Data.Civ2_V);
545            Data.CivStage=Data.CivStage+1;
546        end
547       
548    end
549   
550    %% Patch2
551    if isfield (Param.ActionInput,'Patch2')
552        Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch2_Rho','Patch2_Threshold','Patch2_SubDomain'}];
553        Data.Patch2_FieldSmooth=Param.ActionInput.Patch2.FieldSmooth;
554        Data.Patch2_MaxDiff=Param.ActionInput.Patch2.MaxDiff;
555        Data.Patch2_SubDomainSize=Param.ActionInput.Patch2.SubDomainSize;
556        nbvar=length(Data.ListVarName);
557        Data.ListVarName=[Data.ListVarName {'Civ2_U_smooth','Civ2_V_smooth','Civ2_SubRange','Civ2_NbCentres','Civ2_Coord_tps','Civ2_U_tps','Civ2_V_tps'}];
558        Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2',{'nb_coord','nb_bounds','nb_subdomain_2'},{'nb_subdomain_2'},...
559            {'nb_tps_2','nb_coord','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'}}];
560       
561        Data.VarAttribute{nbvar+1}.Role='vector_x';
562        Data.VarAttribute{nbvar+2}.Role='vector_y';
563        Data.VarAttribute{nbvar+5}.Role='coord_tps';
564        Data.VarAttribute{nbvar+6}.Role='vector_x';
565        Data.VarAttribute{nbvar+7}.Role='vector_y';
566        Data.Civ2_U_smooth=zeros(size(Data.Civ2_X));
567        Data.Civ2_V_smooth=zeros(size(Data.Civ2_X));
568        if isfield(Data,'Civ2_FF')
569            ind_good=find(Data.Civ2_FF==0);
570        else
571            ind_good=1:numel(Data.Civ2_X);
572        end
573        [Data.Civ2_SubRange,Data.Civ2_NbCentres,Data.Civ2_Coord_tps,Data.Civ2_U_tps,Data.Civ2_V_tps,tild,Ures, Vres,tild,FFres]=...
574            filter_tps([Data.Civ2_X(ind_good) Data.Civ2_Y(ind_good)],Data.Civ2_U(ind_good),Data.Civ2_V(ind_good),[],Data.Patch2_SubDomainSize,Data.Patch2_FieldSmooth,Data.Patch2_MaxDiff);
575        Data.Civ2_U_smooth(ind_good)=Ures;
576        Data.Civ2_V_smooth(ind_good)=Vres;
577        Data.Civ2_FF(ind_good)=FFres;
578        Data.CivStage=Data.CivStage+1;
579    end
580   
581    %% write result in a netcdf file if requested
582    if exist('ncfile','var')
583        errormsg=struct2nc(ncfile,Data);
584        if isempty(errormsg)
585            disp([ncfile ' written'])
586        else
587            disp(errormsg)
588        end
589    end
590end
591
592% 'civ': function piv.m adapted from PIVlab http://pivlab.blogspot.com/
593%--------------------------------------------------------------------------
594% function [xtable ytable utable vtable typevector] = civ (image1,image2,ibx,iby step, subpixfinder, mask, roi)
595%
596% OUTPUT:
597% xtable: set of x coordinates
598% ytable: set of y coordiantes
599% utable: set of u displacements (along x)
600% vtable: set of v displacements (along y)
601% ctable: max image correlation for each vector
602% typevector: set of flags, =1 for good, =0 for NaN vectors
603%
604%INPUT:
605% par_civ: structure of input parameters, with fields:
606%  .CorrBoxSize
607%  .SearchBoxSize
608%  .SearchBoxShift
609%  .ImageHeight
610%  .ImageWidth
611%  .Dx, Dy
612%  .Grid
613%  .Mask
614%  .MinIma
615%  .MaxIma
616%  .image1:first image (matrix)
617% image2: second image (matrix)
618% ibx2,iby2: half size of the correlation box along x and y, in px (size=(2*iby2+1,2*ibx2+1)
619% isx2,isy2: half size of the search box along x and y, in px (size=(2*isy2+1,2*isx2+1)
620% shiftx, shifty: shift of the search box (in pixel index, yshift reversed)
621% step: mesh of the measurement points (in px)
622% subpixfinder=1 or 2 controls the curve fitting of the image correlation
623% mask: =[] for no mask
624% roi: 4 element vector defining a region of interest: x position, y position, width, height, (in image indices), for the whole image, roi=[];
625function [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ)
626%this funtion performs the DCC PIV analysis. Recent window-deformation
627%methods perform better and will maybe be implemented in the future.
628
629%% prepare measurement grid
630if isfield(par_civ,'Grid')% grid points set as input
631    if ischar(par_civ.Grid)%read the drid file if the input is a file name
632        par_civ.Grid=dlmread(par_civ.Grid);
633        par_civ.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
634    end
635else% automatic grid
636    minix=floor(par_civ.Dx/2)-0.5;
637    maxix=minix+par_civ.Dx*floor((par_civ.ImageWidth-1)/par_civ.Dx);
638    miniy=floor(par_civ.Dy/2)-0.5;
639    maxiy=minix+par_civ.Dy*floor((par_civ.ImageHeight-1)/par_civ.Dy);
640    [GridX,GridY]=meshgrid(minix:par_civ.Dx:maxix,miniy:par_civ.Dy:maxiy);
641    par_civ.Grid(:,1)=reshape(GridX,[],1);
642    par_civ.Grid(:,2)=reshape(GridY,[],1);
643end
644nbvec=size(par_civ.Grid,1);
645
646%% prepare correlation and search boxes
647ibx2=ceil(par_civ.CorrBoxSize(1)/2);
648iby2=ceil(par_civ.CorrBoxSize(2)/2);
649isx2=ceil(par_civ.SearchBoxSize(1)/2);
650isy2=ceil(par_civ.SearchBoxSize(2)/2);
651shiftx=round(par_civ.SearchBoxShift(:,1));
652shifty=-round(par_civ.SearchBoxShift(:,2));% sign minus because image j index increases when y decreases
653if numel(shiftx)==1% case of a unique shift for the whole field( civ1)
654    shiftx=shiftx*ones(nbvec,1);
655    shifty=shifty*ones(nbvec,1);
656end
657
658%% Default output
659xtable=par_civ.Grid(:,1);
660ytable=par_civ.Grid(:,2);
661utable=zeros(nbvec,1);
662vtable=zeros(nbvec,1);
663ctable=zeros(nbvec,1);
664F=zeros(nbvec,1);
665result_conv=[];
666errormsg='';
667
668%% prepare mask
669if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
670    if strcmp(par_civ.Mask,'all')
671        return    % get the grid only, no civ calculation
672    elseif ischar(par_civ.Mask)
673        par_civ.Mask=imread(par_civ.Mask);
674    end
675end
676check_MinIma=isfield(par_civ,'MinIma');% test for image luminosity threshold
677check_MaxIma=isfield(par_civ,'MaxIma') && ~isempty(par_civ.MaxIma);
678
679% %% prepare images
680% if isfield(par_civ,'reverse_pair')
681%     if par_civ.reverse_pair
682%         if ischar(par_civ.ImageB)
683%             temp=par_civ.ImageA;
684%             par_civ.ImageA=imread(par_civ.ImageB);
685%         end
686%         if ischar(temp)
687%             par_civ.ImageB=imread(temp);
688%         end
689%     end
690% else
691%     if ischar(par_civ.ImageA)
692%         par_civ.ImageA=imread(par_civ.ImageA);
693%     end
694%     if ischar(par_civ.ImageB)
695%         par_civ.ImageB=imread(par_civ.ImageB);
696%     end
697% end
698par_civ.ImageA=sum(double(par_civ.ImageA),3);%sum over rgb component for color images
699par_civ.ImageB=sum(double(par_civ.ImageB),3);
700[npy_ima npx_ima]=size(par_civ.ImageA);
701if ~isequal(size(par_civ.ImageB),[npy_ima npx_ima])
702    errormsg='image pair with unequal size';
703    return
704end
705
706%% Apply mask
707    % Convention for mask IDEAS TO IMPLEMENT ?
708    % mask >200 : velocity calculated
709    %  200 >=mask>150;velocity not calculated, interpolation allowed (bad spots)
710    % 150>=mask >100: velocity not calculated, nor interpolated
711    %  100>=mask> 20: velocity not calculated, impermeable (no flux through mask boundaries)
712    %  20>=mask: velocity=0
713checkmask=0;
714MinA=min(min(par_civ.ImageA));
715MinB=min(min(par_civ.ImageB));
716if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
717   checkmask=1;
718   if ~isequal(size(par_civ.Mask),[npy_ima npx_ima])
719        errormsg='mask must be an image with the same size as the images';
720        return
721   end
722  %  check_noflux=(par_civ.Mask<100) ;%TODO: to implement
723    check_undefined=(par_civ.Mask<200 & par_civ.Mask>=20 );
724    par_civ.ImageA(check_undefined)=MinA;% put image A to zero (i.e. the min image value) in the undefined  area
725    par_civ.ImageB(check_undefined)=MinB;% put image B to zero (i.e. the min image value) in the undefined  area
726end
727
728%% compute image correlations: MAINLOOP on velocity vectors
729corrmax=0;
730sum_square=1;% default
731mesh=1;% default
732CheckDecimal=isfield(par_civ,'CheckDecimal')&& par_civ.CheckDecimal==1;
733if CheckDecimal
734    mesh=0.2;%mesh in pixels for subpixel image interpolation
735    CheckDeformation=isfield(par_civ,'CheckDeformation')&& par_civ.CheckDeformation==1;
736end
737% vector=[0 0];%default
738for ivec=1:nbvec
739    iref=round(par_civ.Grid(ivec,1)+0.5);% xindex on the image A for the middle of the correlation box
740    jref=round(par_civ.ImageHeight-par_civ.Grid(ivec,2)+0.5);% yindex on the image B for the middle of the correlation box
741    %if ~(checkmask && par_civ.Mask(jref,iref)<=20) %velocity not set to zero by the black mask
742    %         if jref-iby2<1 || jref+iby2>par_civ.ImageHeight|| iref-ibx2<1 || iref+ibx2>par_civ.ImageWidth||...
743    %               jref+shifty(ivec)-isy2<1||jref+shifty(ivec)+isy2>par_civ.ImageHeight|| iref+shiftx(ivec)-isx2<1 || iref+shiftx(ivec)+isx2>par_civ.ImageWidth  % we are outside the image
744    %             F(ivec)=3;
745    %         else
746    F(ivec)=0;
747    subrange1_x=iref-ibx2:iref+ibx2;% x indices defining the first subimage
748    subrange1_y=jref-iby2:jref+iby2;% y indices defining the first subimage
749    subrange2_x=iref+shiftx(ivec)-isx2:iref+shiftx(ivec)+isx2;%x indices defining the second subimage
750    subrange2_y=jref+shifty(ivec)-isy2:jref+shifty(ivec)+isy2;%y indices defining the second subimage
751    image1_crop=MinA*ones(numel(subrange1_y),numel(subrange1_x));% default value=min of image A
752    image2_crop=MinA*ones(numel(subrange2_y),numel(subrange2_x));% default value=min of image A
753    check1_x=subrange1_x>=1 & subrange1_x<=par_civ.ImageWidth;% check which points in the subimage 1 are contained in the initial image 1
754    check1_y=subrange1_y>=1 & subrange1_y<=par_civ.ImageHeight;
755    check2_x=subrange2_x>=1 & subrange2_x<=par_civ.ImageWidth;% check which points in the subimage 2 are contained in the initial image 2
756    check2_y=subrange2_y>=1 & subrange2_y<=par_civ.ImageHeight;
757   
758    image1_crop(check1_y,check1_x)=par_civ.ImageA(subrange1_y(check1_y),subrange1_x(check1_x));%extract a subimage (correlation box) from image A
759    image2_crop(check2_y,check2_x)=par_civ.ImageB(subrange2_y(check2_y),subrange2_x(check2_x));%extract a larger subimage (search box) from image B
760    image1_mean=mean(mean(image1_crop));
761    image2_mean=mean(mean(image2_crop));
762    %threshold on image minimum
763    if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
764        F(ivec)=3;
765    end
766    %threshold on image maximum
767    if check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
768        F(ivec)=3;
769    end
770    %         end
771    if F(ivec)~=3
772        image1_crop=image1_crop-image1_mean;%substract the mean
773        image2_crop=image2_crop-image2_mean;
774        if CheckDecimal
775            xi=(1:mesh:size(image1_crop,2));
776            yi=(1:mesh:size(image1_crop,1))';
777            if CheckDeformation
778                [XI,YI]=meshgrid(xi-ceil(size(image1_crop,2)/2),yi-ceil(size(image1_crop,1)/2));
779                XIant=XI-par_civ.DUDX(ivec)*XI-par_civ.DUDY(ivec)*YI+ceil(size(image1_crop,2)/2);
780                YIant=YI-par_civ.DVDX(ivec)*XI-par_civ.DVDY(ivec)*YI+ceil(size(image1_crop,1)/2);
781                image1_crop=interp2(image1_crop,XIant,YIant);
782            else
783                image1_crop=interp2(image1_crop,xi,yi);
784            end
785            xi=(1:mesh:size(image2_crop,2));
786            yi=(1:mesh:size(image2_crop,1))';
787            image2_crop=interp2(image2_crop,xi,yi);
788        end
789        sum_square=sum(sum(image1_crop.*image1_crop));
790        %reference: Oliver Pust, PIV: Direct Cross-Correlation
791        result_conv= conv2(image2_crop,flipdim(flipdim(image1_crop,2),1),'valid');
792        corrmax= max(max(result_conv));
793        result_conv=(result_conv/corrmax)*255; %normalize, peak=always 255
794        %Find the correlation max, at 255
795        [y,x] = find(result_conv==255,1);
796        if ~isempty(y) && ~isempty(x)
797            try
798                if par_civ.CorrSmooth==1
799                    [vector,F(ivec)] = SUBPIXGAUSS (result_conv,x,y);
800                elseif par_civ.CorrSmooth==2
801                    [vector,F(ivec)] = SUBPIX2DGAUSS (result_conv,x,y);
802                end
803                utable(ivec)=vector(1)*mesh+shiftx(ivec);
804                vtable(ivec)=vector(2)*mesh+shifty(ivec);
805                xtable(ivec)=iref+utable(ivec)/2-0.5;% convec flow (velocity taken at the point middle from imgae 1 and 2)
806                ytable(ivec)=jref+vtable(ivec)/2-0.5;% and position of pixel 1=0.5 (convention for image coordinates=0 at the edge)
807                iref=round(xtable(ivec));% image index for the middle of the vector
808                jref=round(ytable(ivec));
809                if checkmask && par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100
810                    utable(ivec)=0;
811                    vtable(ivec)=0;
812                    F(ivec)=3;
813                end
814                ctable(ivec)=corrmax/sum_square;% correlation value
815            catch ME
816                F(ivec)=3;
817            end
818        else
819            F(ivec)=3;
820        end
821    end
822end
823result_conv=result_conv*corrmax/(255*sum_square);% keep the last correlation matrix for output
824
825%------------------------------------------------------------------------
826% --- Find the maximum of the correlation function after interpolation
827function [vector,F] = SUBPIXGAUSS (result_conv,x,y)
828%------------------------------------------------------------------------
829vector=[0 0]; %default
830F=0;
831[npy,npx]=size(result_conv);
832
833% if (x <= (size(result_conv,1)-1)) && (y <= (size(result_conv,1)-1)) && (x >= 1) && (y >= 1)
834    %the following 8 lines are copyright (c) 1998, Uri Shavit, Roi Gurka, Alex Liberzon, Technion ï¿œ Israel Institute of Technology
835    %http://urapiv.wordpress.com
836    peaky = y;
837    if y <= npy-1 && y >= 1
838        f0 = log(result_conv(y,x));
839        f1 = real(log(result_conv(y-1,x)));
840        f2 = real(log(result_conv(y+1,x)));
841        peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
842    else
843        F=-2; % warning flag for vector truncated by the limited search box
844    end
845    peakx=x;
846    if x <= npx-1 && x >= 1
847        f0 = log(result_conv(y,x));
848        f1 = real(log(result_conv(y,x-1)));
849        f2 = real(log(result_conv(y,x+1)));
850        peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
851    else
852        F=-2; % warning flag for vector truncated by the limited search box
853    end
854    vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
855
856%------------------------------------------------------------------------
857% --- Find the maximum of the correlation function after interpolation
858function [vector,F] = SUBPIX2DGAUSS (result_conv,x,y)
859%------------------------------------------------------------------------
860vector=[0 0]; %default
861F=-2;
862peaky=y;
863peakx=x;
864[npy,npx]=size(result_conv);
865if (x <= npx-1) && (y <= npy-1) && (x >= 1) && (y >= 1)
866    F=0;
867    for i=-1:1
868        for j=-1:1
869            %following 15 lines based on
870            %H. Nobach ï¿œ M. Honkanen (2005)
871            %Two-dimensional Gaussian regression for sub-pixel displacement
872            %estimation in particle image velocimetry or particle position
873            %estimation in particle tracking velocimetry
874            %Experiments in Fluids (2005) 38: 511ï¿œ515
875            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
876            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
877            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
878            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
879            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
880        end
881    end
882    c10=(1/6)*sum(sum(c10));
883    c01=(1/6)*sum(sum(c01));
884    c11=(1/4)*sum(sum(c11));
885    c20=(1/6)*sum(sum(c20));
886    c02=(1/6)*sum(sum(c02));
887    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11^2);
888    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11^2);
889    if abs(deltax)<1
890        peakx=x+deltax;
891    end
892    if abs(deltay)<1
893        peaky=y+deltay;
894    end
895end
896vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
897
898%'RUN_FIX': function for fixing velocity fields:
899%-----------------------------------------------
900% RUN_FIX(filename,field,flagindex,thresh_vecC,thresh_vel,iter,flag_mask,maskname,fileref,fieldref)
901%
902%filename: name of the netcdf file (used as input and output)
903%field: structure specifying the names of the fields to fix (depending on civ1 or civ2)
904    %.vel_type='civ1' or 'civ2';
905    %.nb=name of the dimension common to the field to fix ('nb_vectors' for civ1);
906    %.fixflag=name of fix flag variable ('vec_FixFlag' for civ1)
907%flagindex: flag specifying which values of vec_f are removed:
908        % if flagindex(1)=1: vec_f=-2 vectors are removed
909        % if flagindex(2)=1: vec_f=3 vectors are removed
910        % if flagindex(3)=1: vec_f=2 vectors are removed (if iter=1) or vec_f=4 vectors are removed (if iter=2)
911%iter=1 for civ1 fields and iter=2 for civ2 fields
912%thresh_vecC: threshold in the image correlation vec_C
913%flag_mask: =1 mask used to remove vectors (0 else)
914%maskname: name of the mask image file for fix
915%thresh_vel: threshold on velocity, or on the difference with the reference file fileref if exists
916%inf_sup=1: remove values smaller than threshold thresh_vel, =2, larger than threshold
917%fileref: .nc file name for a reference velocity (='': refrence 0 used)
918%fieldref: 'civ1','filter1'...feld used in fileref
919
920function FF=fix(Param,F,C,U,V,X,Y)
921FF=zeros(size(F));%default
922
923%criterium on warn flags
924FlagName={'CheckFmin2','CheckF2','CheckF3','CheckF4'};
925FlagVal=[-2 2 3 4];
926for iflag=1:numel(FlagName)
927    if isfield(Param,FlagName{iflag}) && Param.(FlagName{iflag})
928        FF=(FF==1| F==FlagVal(iflag));
929    end
930end
931%criterium on correlation values
932if isfield (Param,'MinCorr')
933    FF=FF==1 | C<Param.MinCorr;
934end
935if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
936    Umod= U.*U+V.*V;
937    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
938        FF=FF==1 | Umod<(Param.MinVel*Param.MinVel);
939    end
940    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
941        FF=FF==1 | Umod>(Param.MaxVel*Param.MaxVel);
942    end
943end
944
945
946%------------------------------------------------------------------------
947% --- determine the list of index pairs of processing file
948function [i1_series,i2_series,j1_series,j2_series,check_bounds,NomTypeNc]=...
949    find_pair_indices(str_civ,i_series,j_series,MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j)
950%------------------------------------------------------------------------
951i1_series=i_series;% set of first image indexes
952i2_series=i_series;
953j1_series=ones(size(i_series));% set of first image numbers
954j2_series=ones(size(i_series));
955check_bounds=false(size(i_series));
956r=regexp(str_civ,'^\D(?<ind>[i|j])=( -| )(?<num1>\d+)\|(?<num2>\d+)','names');
957if ~isempty(r)
958    mode=['D' r.ind];
959    ind1=str2num(r.num1);
960    ind2=str2num(r.num2);
961else
962    mode='burst';
963    r=regexp(str_civ,'^j= (?<num1>[a-z])-(?<num2>[a-z])','names');
964    if ~isempty(r)
965        NomTypeNc='_1ab';
966    else
967        r=regexp(str_civ,'^j= (?<num1>[A-Z])-(?<num2>[A-Z])','names');
968        if ~isempty(r)
969            NomTypeNc='_1AB';
970        else
971            r=regexp(str_civ,'^j= (?<num1>\d+)-(?<num2>\d+)','names');
972            if ~isempty(r)
973                NomTypeNc='_1_1-2';
974            end           
975        end
976    end
977    if isempty(r)
978        display('wrong pair mode input option')
979    else
980    ind1=stra2num(r.num1);
981    ind2=stra2num(r.num2);
982    end
983end
984if strcmp (mode,'Di')
985    i1_series=i_series-ind1;% set of first image numbers
986    i2_series=i_series+ind2;
987     check_bounds=i1_series<MinIndex_i | i2_series>MaxIndex_i;
988    if isempty(j_series)
989        NomTypeNc='_1-2';
990    else
991        j1_series=j_series;
992        j2_series=j_series;
993        NomTypeNc='_1-2_1';
994    end
995elseif strcmp (mode,'Dj')
996    j1_series=j_series-ind1;
997    j2_series=j_series+ind2;
998    check_bounds=j1_series<MinIndex_j | j2_series>MaxIndex_j;
999    NomTypeNc='_1_1-2';
1000else  %bursts
1001    j1_series=ind1*ones(size(i_series));
1002    j2_series=ind2*ones(size(i_series));
1003end
1004
1005%     if length(indsel)>=1
1006%         firstind=indsel(1);
1007%         lastind=indsel(end);
1008%         set(handles.first_j,'String',num2str(ref_j(firstind)))%update the display of first and last fields
1009%         set(handles.last_j,'String',num2str(ref_j(lastind)))
1010%         ref_j=ref_j(indsel);
1011%         j1_civ1=j1_civ1(indsel);
1012%         j2_civ1=j2_civ1(indsel);
1013%         j1_civ2=j1_civ2(indsel);
1014%         j2_civ2=j2_civ2(indsel);
1015%     end
1016% elseif isequal(mode,'pair j1-j2') %case of bursts (png_old or png_2D)
1017%     displ_num=get(handles.ListPairCiv1,'UserData');
1018%     i1_civ1=ref_i;
1019%     i2_civ1=ref_i;
1020%     j1_civ1=displ_num(1,index_civ1);
1021%     j2_civ1=displ_num(2,index_civ1);
1022%     i1_civ2=ref_i;
1023%     i2_civ2=ref_i;
1024%     j1_civ2=displ_num(1,index_civ2);
1025%     j2_civ2=displ_num(2,index_civ2);
1026% elseif isequal(mode,'displacement')
1027%     i1_civ1=ref_i;
1028%     i2_civ1=ref_i;
1029%     j1_civ1=ref_j;
1030%     j2_civ1=ref_j;
1031%     i1_civ2=ref_i;
1032%     i2_civ2=ref_i;
1033%     j1_civ2=ref_j;
1034%     j2_civ2=ref_j;
1035% end
1036
1037
1038
1039
Note: See TracBrowser for help on using the repository browser.