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

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

option shift and displacement fixed in civ_series

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