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

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