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

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

deformation modified in civ_series and bug corrections

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