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

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

various

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