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

Last change on this file since 860 was 854, checked in by sommeria, 9 years ago

bugrepair

File size: 47.8 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'};%  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'};
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%         
350%         U=Data.Civ1_U*(Rangx(2)-Rangx(1))/(Npx-1);
351%         V=Data.Civ1_V*(Rangy(2)-Rangy(1))/(Npy-1);
352%         [Data.Zphys,Data.Civ1_E]=shift2z(Data.Xphys,Data.Yphys,U,V,XmlData);
353%         if ~isempty(errormsg)
354%             disp_uvmat('ERROR',errormsg,checkrun)
355%             return
356%         end
357    end
358   
359    %% Fix1
360    if isfield (Param.ActionInput,'Fix1')
361        if ~isfield (Param.ActionInput,'Civ1')% if we use existing Civ1, remove previous data beyond Civ1
362            Fix1_attr=find(strcmp('Fix1',Data.ListGlobalAttribute));
363            Data.ListGlobalAttribute(Fix1_attr)=[];
364            for ilist=1:numel(Fix1_attr)
365                Data=rmfield(Data,Data.ListGlobalAttribute{Fix1_attr(ilist)});
366            end
367        end
368        ListFixParam=fieldnames(Param.ActionInput.Fix1);
369        for ilist=1:length(ListFixParam)
370            ParamName=ListFixParam{ilist};
371            ListName=['Fix1_' ParamName];
372            eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
373            eval(['Data.' ListName '=Param.ActionInput.Fix1.' ParamName ';'])
374        end
375        if check_civx
376            if ~isfield(Data,'fix')
377                Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix'];
378                Data.fix=1;
379                Data.ListVarName=[Data.ListVarName {'vec_FixFlag'}];
380                Data.VarDimName=[Data.VarDimName {'nb_vectors'}];
381            end
382            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);
383        else
384            Data.ListVarName=[Data.ListVarName {'Civ1_FF'}];
385            Data.VarDimName=[Data.VarDimName {'nb_vec_1'}];
386            nbvar=length(Data.ListVarName);
387            Data.VarAttribute{nbvar}.Role='errorflag';
388            Data.Civ1_FF=fix(Param.ActionInput.Fix1,Data.Civ1_F,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V);
389            Data.CivStage=2;
390        end
391    end
392    %% Patch1
393    if isfield (Param.ActionInput,'Patch1')
394        if check_civx
395            errormsg='Civ Matlab input needed for patch';
396            disp_uvmat('ERROR',errormsg,checkrun)
397            return
398        end
399       
400        Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch1_Rho','Patch1_Threshold','Patch1_SubDomain'}];
401        Data.Patch1_FieldSmooth=Param.ActionInput.Patch1.FieldSmooth;
402        Data.Patch1_MaxDiff=Param.ActionInput.Patch1.MaxDiff;
403        Data.Patch1_SubDomainSize=Param.ActionInput.Patch1.SubDomainSize;
404        nbvar=length(Data.ListVarName);
405        Data.ListVarName=[Data.ListVarName {'Civ1_U_smooth','Civ1_V_smooth','Civ1_SubRange','Civ1_NbCentres','Civ1_Coord_tps','Civ1_U_tps','Civ1_V_tps'}];
406        Data.VarDimName=[Data.VarDimName {'nb_vec_1','nb_vec_1',{'nb_coord','nb_bounds','nb_subdomain_1'},'nb_subdomain_1',...
407            {'nb_tps_1','nb_coord','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'}}];
408        Data.VarAttribute{nbvar+1}.Role='vector_x';
409        Data.VarAttribute{nbvar+2}.Role='vector_y';
410        Data.VarAttribute{nbvar+5}.Role='coord_tps';
411        Data.VarAttribute{nbvar+6}.Role='vector_x';
412        Data.VarAttribute{nbvar+7}.Role='vector_y';
413        Data.Civ1_U_smooth=zeros(size(Data.Civ1_X));
414        Data.Civ1_V_smooth=zeros(size(Data.Civ1_X));
415        if isfield(Data,'Civ1_FF')
416            ind_good=find(Data.Civ1_FF==0);
417        else
418            ind_good=1:numel(Data.Civ1_X);
419        end
420        [Data.Civ1_SubRange,Data.Civ1_NbCentres,Data.Civ1_Coord_tps,Data.Civ1_U_tps,Data.Civ1_V_tps,tild,Ures, Vres,tild,FFres]=...
421            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);
422        Data.Civ1_U_smooth(ind_good)=Ures;
423        Data.Civ1_V_smooth(ind_good)=Vres;
424        Data.Civ1_FF(ind_good)=FFres;
425        Data.CivStage=3;
426    end
427   
428    %% Civ2
429    if isfield (Param.ActionInput,'Civ2')
430        par_civ2=Param.ActionInput.Civ2;
431        par_civ2.ImageA=par_civ1.ImageA;
432        par_civ2.ImageB=par_civ1.ImageB;
433        %         if ~isfield(Param.Civ1,'ImageA')
434        i1=i1_series_Civ2(ifield);
435        i2=i1;
436        if ~isempty(i2_series_Civ2)
437            i2=i2_series_Civ2(ifield);
438        end
439        j1=1;
440        if ~isempty(j1_series_Civ2)
441            j1=j1_series_Civ2(ifield);
442        end
443        j2=j1;
444        if ~isempty(j2_series_Civ2)
445            j2=j2_series_Civ2(ifield);
446        end
447        par_civ2.ImageWidth=size(par_civ2.ImageA,2);%FileInfo_A.Width;
448        par_civ2.ImageHeight=size(par_civ2.ImageA,1);%FileInfo_A.Height;
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','Xphys','Yphys','Zphys','Civ2_E'}];%  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','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         % get z from u and v (displacements)
600       
601        Data.Xphys=Rangx(1)+(Rangx(2)-Rangx(1))*(Data.Civ2_X-0.5)/(Npx-1);
602        Data.Yphys=Rangy(1)+(Rangy(2)-Rangy(1))*(Data.Civ2_Y-0.5)/(Npy-1);
603        U=Data.Civ2_U_smooth*(Rangx(2)-Rangx(1))/(Npx-1);
604        V=Data.Civ2_V_smooth*(Rangy(2)-Rangy(1))/(Npy-1);
605        [Data.Zphys,Data.Civ2_E]=shift2z(Data.Xphys,Data.Yphys,U,V,XmlData);
606        if ~isempty(errormsg)
607            disp_uvmat('ERROR',errormsg,checkrun)
608            return
609        end
610       
611    end
612   
613    %% write result in a netcdf file if requested
614    if exist('ncfile','var')
615        errormsg=struct2nc(ncfile,Data);
616        if isempty(errormsg)
617            disp([ncfile ' written'])
618        else
619            disp(errormsg)
620        end
621    end
622end
623
624% 'civ': function piv.m adapted from PIVlab http://pivlab.blogspot.com/
625%--------------------------------------------------------------------------
626% function [xtable ytable utable vtable typevector] = civ (image1,image2,ibx,iby step, subpixfinder, mask, roi)
627%
628% OUTPUT:
629% xtable: set of x coordinates
630% ytable: set of y coordiantes
631% utable: set of u displacements (along x)
632% vtable: set of v displacements (along y)
633% ctable: max image correlation for each vector
634% typevector: set of flags, =1 for good, =0 for NaN vectors
635%
636%INPUT:
637% par_civ: structure of input parameters, with fields:
638%  .CorrBoxSize
639%  .SearchBoxSize
640%  .SearchBoxShift
641%  .ImageHeight
642%  .ImageWidth
643%  .Dx, Dy
644%  .Grid
645%  .Mask
646%  .MinIma
647%  .MaxIma
648%  .image1:first image (matrix)
649% image2: second image (matrix)
650% ibx2,iby2: half size of the correlation box along x and y, in px (size=(2*iby2+1,2*ibx2+1)
651% isx2,isy2: half size of the search box along x and y, in px (size=(2*isy2+1,2*isx2+1)
652% shiftx, shifty: shift of the search box (in pixel index, yshift reversed)
653% step: mesh of the measurement points (in px)
654% subpixfinder=1 or 2 controls the curve fitting of the image correlation
655% mask: =[] for no mask
656% roi: 4 element vector defining a region of interest: x position, y position, width, height, (in image indices), for the whole image, roi=[];
657function [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ)
658%this funtion performs the DCC PIV analysis. Recent window-deformation
659%methods perform better and will maybe be implemented in the future.
660
661%% prepare measurement grid
662if isfield(par_civ,'Grid')% grid points set as input
663    if ischar(par_civ.Grid)%read the drid file if the input is a file name
664        par_civ.Grid=dlmread(par_civ.Grid);
665        par_civ.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
666    end
667else% automatic grid
668    minix=floor(par_civ.Dx/2)-0.5;
669    maxix=minix+par_civ.Dx*floor((par_civ.ImageWidth-1)/par_civ.Dx);
670    miniy=floor(par_civ.Dy/2)-0.5;
671    maxiy=minix+par_civ.Dy*floor((par_civ.ImageHeight-1)/par_civ.Dy);
672    [GridX,GridY]=meshgrid(minix:par_civ.Dx:maxix,miniy:par_civ.Dy:maxiy);
673    par_civ.Grid(:,1)=reshape(GridX,[],1);
674    par_civ.Grid(:,2)=reshape(GridY,[],1);
675end
676nbvec=size(par_civ.Grid,1);
677
678%% prepare correlation and search boxes
679ibx2=ceil(par_civ.CorrBoxSize(1)/2);
680iby2=ceil(par_civ.CorrBoxSize(2)/2);
681isx2=ceil(par_civ.SearchBoxSize(1)/2);
682isy2=ceil(par_civ.SearchBoxSize(2)/2);
683shiftx=round(par_civ.SearchBoxShift(:,1));
684shifty=-round(par_civ.SearchBoxShift(:,2));% sign minus because image j index increases when y decreases
685if numel(shiftx)==1% case of a unique shift for the whole field( civ1)
686    shiftx=shiftx*ones(nbvec,1);
687    shifty=shifty*ones(nbvec,1);
688end
689
690%% Default output
691xtable=par_civ.Grid(:,1);
692ytable=par_civ.Grid(:,2);
693utable=zeros(nbvec,1);
694vtable=zeros(nbvec,1);
695ctable=zeros(nbvec,1);
696F=zeros(nbvec,1);
697result_conv=[];
698errormsg='';
699
700%% prepare mask
701if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
702    if strcmp(par_civ.Mask,'all')
703        return    % get the grid only, no civ calculation
704    elseif ischar(par_civ.Mask)
705        par_civ.Mask=imread(par_civ.Mask);
706    end
707end
708check_MinIma=isfield(par_civ,'MinIma');% test for image luminosity threshold
709check_MaxIma=isfield(par_civ,'MaxIma') && ~isempty(par_civ.MaxIma);
710
711% %% prepare images
712% if isfield(par_civ,'reverse_pair')
713%     if par_civ.reverse_pair
714%         if ischar(par_civ.ImageB)
715%             temp=par_civ.ImageA;
716%             par_civ.ImageA=imread(par_civ.ImageB);
717%         end
718%         if ischar(temp)
719%             par_civ.ImageB=imread(temp);
720%         end
721%     end
722% else
723%     if ischar(par_civ.ImageA)
724%         par_civ.ImageA=imread(par_civ.ImageA);
725%     end
726%     if ischar(par_civ.ImageB)
727%         par_civ.ImageB=imread(par_civ.ImageB);
728%     end
729% end
730par_civ.ImageA=sum(double(par_civ.ImageA),3);%sum over rgb component for color images
731par_civ.ImageB=sum(double(par_civ.ImageB),3);
732[npy_ima npx_ima]=size(par_civ.ImageA);
733if ~isequal(size(par_civ.ImageB),[npy_ima npx_ima])
734    errormsg='image pair with unequal size';
735    return
736end
737
738%% Apply mask
739    % Convention for mask IDEAS TO IMPLEMENT ?
740    % mask >200 : velocity calculated
741    %  200 >=mask>150;velocity not calculated, interpolation allowed (bad spots)
742    % 150>=mask >100: velocity not calculated, nor interpolated
743    %  100>=mask> 20: velocity not calculated, impermeable (no flux through mask boundaries)
744    %  20>=mask: velocity=0
745checkmask=0;
746MinA=min(min(par_civ.ImageA));
747MinB=min(min(par_civ.ImageB));
748if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
749   checkmask=1;
750   if ~isequal(size(par_civ.Mask),[npy_ima npx_ima])
751        errormsg='mask must be an image with the same size as the images';
752        return
753   end
754  %  check_noflux=(par_civ.Mask<100) ;%TODO: to implement
755    check_undefined=(par_civ.Mask<200 & par_civ.Mask>=20 );
756    par_civ.ImageA(check_undefined)=MinA;% put image A to zero (i.e. the min image value) in the undefined  area
757    par_civ.ImageB(check_undefined)=MinB;% put image B to zero (i.e. the min image value) in the undefined  area
758end
759
760%% compute image correlations: MAINLOOP on velocity vectors
761corrmax=0;
762sum_square=1;% default
763mesh=1;% default
764CheckDecimal=isfield(par_civ,'CheckDecimal')&& par_civ.CheckDecimal==1;
765if CheckDecimal
766    mesh=0.2;%mesh in pixels for subpixel image interpolation
767    CheckDeformation=isfield(par_civ,'CheckDeformation')&& par_civ.CheckDeformation==1;
768end
769% vector=[0 0];%default
770for ivec=1:nbvec
771    iref=round(par_civ.Grid(ivec,1)+0.5);% xindex on the image A for the middle of the correlation box
772    jref=round(par_civ.ImageHeight-par_civ.Grid(ivec,2)+0.5);% yindex on the image B for the middle of the correlation box
773    %if ~(checkmask && par_civ.Mask(jref,iref)<=20) %velocity not set to zero by the black mask
774    %         if jref-iby2<1 || jref+iby2>par_civ.ImageHeight|| iref-ibx2<1 || iref+ibx2>par_civ.ImageWidth||...
775    %               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
776    %             F(ivec)=3;
777    %         else
778    F(ivec)=0;
779    subrange1_x=iref-ibx2:iref+ibx2;% x indices defining the first subimage
780    subrange1_y=jref-iby2:jref+iby2;% y indices defining the first subimage
781    subrange2_x=iref+shiftx(ivec)-isx2:iref+shiftx(ivec)+isx2;%x indices defining the second subimage
782    subrange2_y=jref+shifty(ivec)-isy2:jref+shifty(ivec)+isy2;%y indices defining the second subimage
783    image1_crop=MinA*ones(numel(subrange1_y),numel(subrange1_x));% default value=min of image A
784    image2_crop=MinA*ones(numel(subrange2_y),numel(subrange2_x));% default value=min of image A
785    check1_x=subrange1_x>=1 & subrange1_x<=par_civ.ImageWidth;% check which points in the subimage 1 are contained in the initial image 1
786    check1_y=subrange1_y>=1 & subrange1_y<=par_civ.ImageHeight;
787    check2_x=subrange2_x>=1 & subrange2_x<=par_civ.ImageWidth;% check which points in the subimage 2 are contained in the initial image 2
788    check2_y=subrange2_y>=1 & subrange2_y<=par_civ.ImageHeight;
789   
790    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
791    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
792    image1_mean=mean(mean(image1_crop));
793    image2_mean=mean(mean(image2_crop));
794    %threshold on image minimum
795    if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
796        F(ivec)=3;
797    end
798    %threshold on image maximum
799    if check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
800        F(ivec)=3;
801    end
802    %         end
803    if F(ivec)~=3
804        image1_crop=image1_crop-image1_mean;%substract the mean
805        image2_crop=image2_crop-image2_mean;
806        if CheckDecimal
807            xi=(1:mesh:size(image1_crop,2));
808            yi=(1:mesh:size(image1_crop,1))';
809            if CheckDeformation
810                [XI,YI]=meshgrid(xi-ceil(size(image1_crop,2)/2),yi-ceil(size(image1_crop,1)/2));
811                XIant=XI-par_civ.DUDX(ivec)*XI-par_civ.DUDY(ivec)*YI+ceil(size(image1_crop,2)/2);
812                YIant=YI-par_civ.DVDX(ivec)*XI-par_civ.DVDY(ivec)*YI+ceil(size(image1_crop,1)/2);
813                image1_crop=interp2(image1_crop,XIant,YIant);
814            else
815                image1_crop=interp2(image1_crop,xi,yi);
816            end
817            xi=(1:mesh:size(image2_crop,2));
818            yi=(1:mesh:size(image2_crop,1))';
819            image2_crop=interp2(image2_crop,xi,yi);
820        end
821        sum_square=(sum(sum(image1_crop.*image1_crop))+sum(sum(image2_crop.*image2_crop)))/2;
822        %reference: Oliver Pust, PIV: Direct Cross-Correlation
823        result_conv= conv2(image2_crop,flipdim(flipdim(image1_crop,2),1),'valid');
824        corrmax= max(max(result_conv));
825        result_conv=(result_conv/corrmax)*255; %normalize, peak=always 255
826        %Find the correlation max, at 255
827        [y,x] = find(result_conv==255,1);
828        if ~isempty(y) && ~isempty(x)
829            try
830                if par_civ.CorrSmooth==1
831                    [vector,F(ivec)] = SUBPIXGAUSS (result_conv,x,y);
832                elseif par_civ.CorrSmooth==2
833                    [vector,F(ivec)] = SUBPIX2DGAUSS (result_conv,x,y);
834                end
835
836%                 if isfield(par_civ,'CheckDeformation')
837%                  utable(ivec)=shiftx(ivec);
838%                  vtable(ivec)=shifty(ivec);
839%                 else
840                 utable(ivec)=vector(1)*mesh+shiftx(ivec);
841                vtable(ivec)=vector(2)*mesh+shifty(ivec);
842%                 end
843%                 xtable(ivec)=iref+utable(ivec)/2-0.5;% convec flow (velocity taken at the point middle from imgae 1 and 2)
844%                 ytable(ivec)=jref+vtable(ivec)/2-0.5;% and position of pixel 1=0.5 (convention for image coordinates=0 at the edge)
845                iref=round(xtable(ivec));% image index for the middle of the vector
846                jref=round(ytable(ivec));
847                if checkmask && par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100
848                    utable(ivec)=0;
849                    vtable(ivec)=0;
850                    F(ivec)=3;
851                end
852                ctable(ivec)=corrmax/sum_square;% correlation value
853            catch ME
854                F(ivec)=3;
855            end
856        else
857            F(ivec)=3;
858        end
859    end
860end
861result_conv=result_conv*corrmax/(255*sum_square);% keep the last correlation matrix for output
862
863%------------------------------------------------------------------------
864% --- Find the maximum of the correlation function after interpolation
865function [vector,F] = SUBPIXGAUSS (result_conv,x,y)
866%------------------------------------------------------------------------
867vector=[0 0]; %default
868F=0;
869[npy,npx]=size(result_conv);
870result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1 (to avoid divergence in the log)
871%the following 8 lines are copyright (c) 1998, Uri Shavit, Roi Gurka, Alex Liberzon, Technion ᅵ Israel Institute of Technology
872%http://urapiv.wordpress.com
873peaky = y;
874if y <= npy-1 && y >= 1
875    f0 = log(result_conv(y,x));
876    f1 = log(result_conv(y-1,x));
877    f2 = log(result_conv(y+1,x));
878    peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
879else
880    F=-2; % warning flag for vector truncated by the limited search box
881end
882peakx=x;
883if x <= npx-1 && x >= 1
884    f0 = log(result_conv(y,x));
885    f1 = log(result_conv(y,x-1));
886    f2 = log(result_conv(y,x+1));
887    peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
888else
889    F=-2; % warning flag for vector truncated by the limited search box
890end
891vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
892
893%------------------------------------------------------------------------
894% --- Find the maximum of the correlation function after interpolation
895function [vector,F] = SUBPIX2DGAUSS (result_conv,x,y)
896%------------------------------------------------------------------------
897vector=[0 0]; %default
898F=-2;
899peaky=y;
900peakx=x;
901result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1 (to avoid divergence in the log)
902[npy,npx]=size(result_conv);
903if (x <= npx-1) && (y <= npy-1) && (x >= 1) && (y >= 1)
904    F=0;
905    for i=-1:1
906        for j=-1:1
907            %following 15 lines based on
908            %H. Nobach ï¿œ M. Honkanen (2005)
909            %Two-dimensional Gaussian regression for sub-pixel displacement
910            %estimation in particle image velocimetry or particle position
911            %estimation in particle tracking velocimetry
912            %Experiments in Fluids (2005) 38: 511ï¿œ515
913            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
914            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
915            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
916            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
917            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
918        end
919    end
920    c10=(1/6)*sum(sum(c10));
921    c01=(1/6)*sum(sum(c01));
922    c11=(1/4)*sum(sum(c11));
923    c20=(1/6)*sum(sum(c20));
924    c02=(1/6)*sum(sum(c02));
925    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11^2);
926    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11^2);
927    if abs(deltax)<1
928        peakx=x+deltax;
929    end
930    if abs(deltay)<1
931        peaky=y+deltay;
932    end
933end
934vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
935
936%'RUN_FIX': function for fixing velocity fields:
937%-----------------------------------------------
938% RUN_FIX(filename,field,flagindex,thresh_vecC,thresh_vel,iter,flag_mask,maskname,fileref,fieldref)
939%
940%filename: name of the netcdf file (used as input and output)
941%field: structure specifying the names of the fields to fix (depending on civ1 or civ2)
942    %.vel_type='civ1' or 'civ2';
943    %.nb=name of the dimension common to the field to fix ('nb_vectors' for civ1);
944    %.fixflag=name of fix flag variable ('vec_FixFlag' for civ1)
945%flagindex: flag specifying which values of vec_f are removed:
946        % if flagindex(1)=1: vec_f=-2 vectors are removed
947        % if flagindex(2)=1: vec_f=3 vectors are removed
948        % if flagindex(3)=1: vec_f=2 vectors are removed (if iter=1) or vec_f=4 vectors are removed (if iter=2)
949%iter=1 for civ1 fields and iter=2 for civ2 fields
950%thresh_vecC: threshold in the image correlation vec_C
951%flag_mask: =1 mask used to remove vectors (0 else)
952%maskname: name of the mask image file for fix
953%thresh_vel: threshold on velocity, or on the difference with the reference file fileref if exists
954%inf_sup=1: remove values smaller than threshold thresh_vel, =2, larger than threshold
955%fileref: .nc file name for a reference velocity (='': refrence 0 used)
956%fieldref: 'civ1','filter1'...feld used in fileref
957
958function FF=fix(Param,F,C,U,V,X,Y)
959FF=zeros(size(F));%default
960
961%criterium on warn flags
962FlagName={'CheckFmin2','CheckF2','CheckF3','CheckF4'};
963FlagVal=[-2 2 3 4];
964for iflag=1:numel(FlagName)
965    if isfield(Param,FlagName{iflag}) && Param.(FlagName{iflag})
966        FF=(FF==1| F==FlagVal(iflag));
967    end
968end
969%criterium on correlation values
970if isfield (Param,'MinCorr')
971    FF=FF==1 | C<Param.MinCorr;
972end
973if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
974    Umod= U.*U+V.*V;
975    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
976        FF=FF==1 | Umod<(Param.MinVel*Param.MinVel);
977    end
978    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
979        FF=FF==1 | Umod>(Param.MaxVel*Param.MaxVel);
980    end
981end
982
983
984%------------------------------------------------------------------------
985% --- determine the list of index pairs of processing file
986function [i1_series,i2_series,j1_series,j2_series,check_bounds,NomTypeNc]=...
987    find_pair_indices(str_civ,i_series,j_series,MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j)
988%------------------------------------------------------------------------
989i1_series=i_series;% set of first image indexes
990i2_series=i_series;
991j1_series=j_series;%ones(size(i_series));% set of first image numbers
992j2_series=j_series;%ones(size(i_series));
993r=regexp(str_civ,'^\D(?<ind>[i|j])=( -| )(?<num1>\d+)\|(?<num2>\d+)','names');
994if ~isempty(r)
995    mode=['D' r.ind];
996    ind1=str2num(r.num1);
997    ind2=str2num(r.num2);
998else
999    mode='j1-j2';
1000    r=regexp(str_civ,'^j= (?<num1>[a-z])-(?<num2>[a-z])','names');
1001    if ~isempty(r)
1002        NomTypeNc='_1ab';
1003    else
1004        r=regexp(str_civ,'^j= (?<num1>[A-Z])-(?<num2>[A-Z])','names');
1005        if ~isempty(r)
1006            NomTypeNc='_1AB';
1007        else
1008            r=regexp(str_civ,'^j= (?<num1>\d+)-(?<num2>\d+)','names');
1009            if ~isempty(r)
1010                NomTypeNc='_1_1-2';
1011            end           
1012        end
1013    end
1014    if isempty(r)
1015        display('wrong pair mode input option')
1016    else
1017    ind1=stra2num(r.num1);
1018    ind2=stra2num(r.num2);
1019    end
1020end
1021switch mode
1022    case 'Di'
1023        i1_series=i_series-ind1;% set of first image numbers
1024        i2_series=i_series+ind2;
1025        check_bounds=i1_series<MinIndex_i | i2_series>MaxIndex_i;
1026        if isempty(j_series)
1027            NomTypeNc='_1-2';
1028        else
1029            j1_series=j_series;
1030            j2_series=j_series;
1031            NomTypeNc='_1-2_1';
1032        end
1033    case 'Dj'
1034        j1_series=j_series-ind1;
1035        j2_series=j_series+ind2;
1036        check_bounds=j1_series<MinIndex_j | j2_series>MaxIndex_j;
1037        NomTypeNc='_1_1-2';
1038    otherwise %bursts
1039        i1_series=i_series(1,:);% do not sweep the j index
1040        i2_series=i_series(1,:);
1041        j1_series=ind1*ones(1,size(i_series,2));% j index is fixed by pair choice
1042        j2_series=ind2*ones(1,size(i_series,2));
1043        check_bounds=zeros(size(i1_series));% no limitations due to min-max indices
1044end
1045
1046%INPUT:
1047% xmid- u/2: set of apparent phys x coordinates in the ref plane, image A
1048% ymid- v/2: set of apparent phys y coordinates in the ref plane, image A
1049% xmid+ u/2: set of apparent phys x coordinates in the ref plane, image B
1050% ymid+ v/2: set of apparent phys y coordinates in the ref plane, image B
1051% XmlData: content of the xml files containing geometric calibration parameters
1052function [z,error]=shift2z(xmid, ymid, u, v,XmlData)
1053z=0;
1054error=0;
1055
1056
1057%% first image
1058Calib_A=XmlData{1}.GeometryCalib;
1059R=(Calib_A.R)';
1060x_a=xmid;
1061y_a=ymid;
1062z_a=R(7)*x_a+R(8)*y_a+Calib_A.Tx_Ty_Tz(1,3);
1063Xa=(R(1)*x_a+R(2)*y_a+Calib_A.Tx_Ty_Tz(1,1))./z_a;
1064Ya=(R(4)*x_a+R(5)*y_a+Calib_A.Tx_Ty_Tz(1,2))./z_a;
1065
1066A_1_1=R(1)-R(7)*Xa;
1067A_1_2=R(2)-R(8)*Xa;
1068A_1_3=R(3)-R(9)*Xa;
1069A_2_1=R(4)-R(7)*Ya;
1070A_2_2=R(5)-R(8)*Ya;
1071A_2_3=R(6)-R(9)*Ya;
1072Det=A_1_1.*A_2_2-A_1_2.*A_2_1;
1073Dxa=(A_1_2.*A_2_3-A_2_2.*A_1_3)./Det;
1074Dya=(A_2_1.*A_1_3-A_1_1.*A_2_3)./Det;
1075
1076%% second image
1077Calib_B=XmlData{2}.GeometryCalib;
1078R=(Calib_B.R)';
1079x_b=xmid+ u;
1080y_b=ymid+ v;
1081z_b=R(7)*x_b+R(8)*y_b+Calib_B.Tx_Ty_Tz(1,3);
1082Xb=(R(1)*x_b+R(2)*y_b+Calib_B.Tx_Ty_Tz(1,1))./z_b;
1083Yb=(R(4)*x_b+R(5)*y_b+Calib_B.Tx_Ty_Tz(1,2))./z_b;
1084B_1_1=R(1)-R(7)*Xb;
1085B_1_2=R(2)-R(8)*Xb;
1086B_1_3=R(3)-R(9)*Xb;
1087B_2_1=R(4)-R(7)*Yb;
1088B_2_2=R(5)-R(8)*Yb;
1089B_2_3=R(6)-R(9)*Yb;
1090Det=B_1_1.*B_2_2-B_1_2.*B_2_1;
1091Dxb=(B_1_2.*B_2_3-B_2_2.*B_1_3)./Det;
1092Dyb=(B_2_1.*B_1_3-B_1_1.*B_2_3)./Det;
1093
1094%% result
1095Den=(Dxb-Dxa).*(Dxb-Dxa)+(Dyb-Dya).*(Dyb-Dya);
1096error=((Dyb-Dya).*u-(Dxb-Dxa).*v)./Den;
1097z=((Dxb-Dxa).*u-(Dyb-Dya).*v)./Den;
1098
Note: See TracBrowser for help on using the repository browser.