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

Last change on this file since 1118 was 1118, checked in by sommeria, 3 years ago

civdata from get_field repaired, detail data output activated in stereo_civ

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