source: trunk/src/series/stereo_civ.m

Last change on this file was 1161, checked in by sommeria, 3 months ago

filter_tps modified to avoid possible bugs in case of few vectors, subpixel interpolation slightly modified in civ

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