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

Last change on this file since 985 was 985, checked in by sommeria, 8 years ago

image with vectors fixed

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