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

Last change on this file since 711 was 711, checked in by sommeria, 10 years ago

various improvements

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