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

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

bugs corrected in stereo_civ

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