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

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

bug corrected in civ: log becomes imaginary in max correlation fit

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