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

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