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

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