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

Last change on this file since 1133 was 1126, checked in by g7moreau, 6 months ago

Update Copyright

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