source: trunk/src/series/stereo_civ.m @ 844

Last change on this file since 844 was 844, checked in by sommeria, 6 years ago

various bugs repaired

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