source: trunk/src/series/civ_3D.m @ 1148

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

civ_3D corrected

File size: 53.8 KB
Line 
1%'civ_3D': 3D PIV from image scan in a volume
2
3%------------------------------------------------------------------------
4% function [Data,errormsg,result_conv]= civ_3D(Param)
5%
6%OUTPUT
7% Data=structure containing the PIV results and information on the processing parameters
8% errormsg=error message char string, decd ..fault=''
9% resul_conv: image inter-correlation function for the last grid point (used for tests)
10%
11%INPUT:
12% Param: Matlab structure of input  parameters
13%     Param contains info of the GUI series using the fct read_GUI.
14%     Param.Action.RUN = 0 (to set the status of the GUI series) or =1 to RUN the computation
15%     Param.InputTable: sets the input file(s)
16%           if absent, the fct looks for input data in Param.ActionInput     (test mode)
17%     Param.OutputSubDir: sets the folder name of output file(s,
18%           if absent no file is produced, result in the output structure Data (test mode)
19%     Param.ActionInput: substructure with the parameters provided by the GUI civ_input
20%                      .Civ1: parameters for civ1cc
21%                      .Fix1: parameters for detect_false1
22%                      .Patch1:
23%                      .Civ2: for civ2
24%                      .Fix2:
25%                      .Patch2:
26
27%=======================================================================
28% Copyright 2008-2024, LEGI UMR 5519 / CNRS UGA G-INP, Grenoble, France
29%   http://www.legi.grenoble-inp.fr
30%   Joel.Sommeria - Joel.Sommeria (A) univ-grenoble-alpes.fr
31%
32%     This file is part of the toolbox UVMAT.
33%
34%     UVMAT is free software; you can redistribute it and/or modify
35%     it under the terms of the GNU General Public License as published
36%     by the Free Software Foundation; either version 2 of the license,
37%     or (at your option) any later version.
38%
39%     UVMAT is distributed in the hope that it will be useful,
40%     but WITHOUT ANY WARRANTY; without even the implied warranty of
41%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
42%     GNU General Public License (see LICENSE.txt) for more details.
43%=======================================================================
44
45function [Data,errormsg,result_conv]= civ_3D(Param)
46errormsg='';
47
48%% set the input elements needed on the GUI series when the action is selected in the menu ActionName or InputTable refreshed
49if isstruct(Param) && isequal(Param.Action.RUN,0)% function activated from the GUI series but not RUN
50    path_series=fileparts(which('series'));
51    addpath(fullfile(path_series,'series'))
52
53   Data=civ_input(Param)
54
55    Data.Program=mfilename;%gives the name of the current function
56    Data.AllowInputSort='off';% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
57    Data.WholeIndexRange_j='on';% prescribes the file index ranges j 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='on';% 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
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='.civ_3D';%set the output dir extension
65    Data.OutputSubDirMode='last'; %select the last subDir in the input table as root of the output subdir name (option 'all'/'first'/'last', 'all' by default)
66    Data.OutputFileMode='NbInput_i';% one output file expected per value of i index (used for waitbar)
67    Data.CheckOverwriteVisible='on'; % manage the overwrite of existing files (default=1)
68    if isfield(Data,'ActionInput') && isfield(Data.ActionInput,'PairIndices') && strcmp(Data.ActionInput.PairIndices.ListPairMode,'pair j1-j2')
69        if isfield(Data.ActionInput.PairIndices,'ListPairCiv2')
70            str_civ=Data.ActionInput.PairIndices.ListPairCiv2;
71        else
72            str_civ=Data.ActionInput.PairIndices.ListPairCiv1;
73        end
74        r=regexp(str_civ,'^j= (?<num1>[a-z])-(?<num2>[a-z])','names');
75        if isempty(r)
76            r=regexp(str_civ,'^j= (?<num1>[A-Z])-(?<num2>[A-Z])','names');
77            if isempty(r)
78                r=regexp(str_civ,'^j= (?<num1>\d+)-(?<num2>\d+)','names');
79            end
80        end
81        if ~isempty(r)
82            Data.j_index_1=stra2num(r.num1);
83            Data.j_index_2=stra2num(r.num2);
84        end
85    end
86
87
88    return
89end
90%% END OF ENTERING INPUT PARAMETER MODE
91
92%% RUN MODE: read input parameters from an xml file if input is a file name (batch mode)
93if ischar(Param)
94    Param=xml2struct(Param);% read Param as input file (batch case)
95    checkrun=0;
96    RUNHandle=[];
97else
98    hseries=findobj(allchild(0),'Tag','series');
99    RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
100    WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
101    checkrun=1;
102end
103
104%% test input Param
105if ~isfield(Param,'InputTable')
106    disp('ERROR: no input file entered')
107    return
108end
109if ~isfield(Param,'ActionInput')
110    disp_uvmat('ERROR','no parameter set for PIV',checkrun)
111    return
112end
113iview_A=0;%default values
114
115if isfield(Param,'OutputSubDir')&& isfield(Param,'OutputDirExt')
116    OutputDir=[Param.OutputSubDir Param.OutputDirExt];
117     OutputPath=fullfile(Param.OutputPath,num2str(Param.Experiment),num2str(Param.Device));
118else
119    disp_uvmat('ERROR','no output folder defined',checkrun)
120    return
121end
122
123%% input files and indexing
124MaxIndex_i=Param.IndexRange.MaxIndex_i;
125MinIndex_i=Param.IndexRange.MinIndex_i;
126MaxIndex_j=ones(size(MaxIndex_i));MinIndex_j=ones(size(MinIndex_i));
127if isfield(Param.IndexRange,'MaxIndex_j')&& isfield(Param.IndexRange,'MinIndex_j')
128    MaxIndex_j=Param.IndexRange.MaxIndex_j;
129    MinIndex_j=Param.IndexRange.MinIndex_j;
130end
131
132[tild,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
133iview_A=0;% series index (iview) for the first image series
134iview_B=0;% series index (iview) for the second image series (only non zero for option 'shift' comparing two image series )
135if Param.ActionInput.CheckCiv1
136    iview_A=1;% usual PIV, the image series is on the first line of the table
137elseif Param.ActionInput.CheckCiv2 % civ2 is performed without Civ1, a netcdf file series is needed in the first table line
138    iview_A=2;% the second line is used for the input images of Civ2
139end
140if iview_A~=0
141    RootPath_A=Param.InputTable{iview_A,1};
142    RootFile_A=Param.InputTable{iview_A,3};
143    SubDir_A=Param.InputTable{iview_A,2};
144    NomType_A=Param.InputTable{iview_A,4};
145    FileExt_A=Param.InputTable{iview_A,5};
146    if iview_B==0
147        iview_B=iview_A;% the second image series is the same as the first
148    end
149    RootPath_B=Param.InputTable{iview_B,1};
150    RootFile_B=Param.InputTable{iview_B,3};
151    SubDir_B=Param.InputTable{iview_B,2};
152    NomType_B=Param.InputTable{iview_B,4};
153    FileExt_B=Param.InputTable{iview_B,5};
154end
155
156PairCiv1=Param.ActionInput.PairIndices.ListPairCiv1;
157
158[i1_series_Civ1,i2_series_Civ1,j1_series_Civ1,j2_series_Civ1,check_bounds,NomTypeNc]=...
159                        find_pair_indices(PairCiv1,i1_series{1},j1_series{1},MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j);
160                   
161if isempty(i1_series_Civ1)
162    disp_uvmat('ERROR','no image pair for civ in the input file index range',checkrun)
163    return
164end
165NbField_i=size(i1_series_Civ1,2);
166NbSlice=size(i1_series_Civ1,1);
167
168%% prepare output Data
169ListGlobalAttribute={'Conventions','Program','CivStage'};
170Data.Conventions='uvmat/civdata';% states the conventions used for the description of field variables and attributes
171Data.Program='civ_series';
172Data.CivStage=0;%default
173list_param=(fieldnames(Param.ActionInput.Civ1))';
174    list_param(strcmp('TestCiv1',list_param))=[];% remove the parameter TestCiv1 from the list
175    Civ1_param=regexprep(list_param,'^.+','Civ1_$0');% insert 'Civ1_' before  each string in list_param
176    Civ1_param=[{'Civ1_ImageA','Civ1_ImageB','Civ1_Time','Civ1_Dt'} Civ1_param]; %insert the names of the two input images
177Data.ListGlobalAttribute=[ListGlobalAttribute Civ1_param];
178            % set the list of variables
179        Data.ListVarName={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_W','Civ1_C','Civ1_FF'};%  cell array containing the names of the fields to record
180        Data.VarDimName={'nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1'};
181        Data.VarAttribute{1}.Role='coord_x';
182        Data.VarAttribute{2}.Role='coord_y';
183        Data.VarAttribute{3}.Role='vector_x';
184        Data.VarAttribute{4}.Role='vector_y';
185        Data.VarAttribute{5}.Role='vector_z';
186        Data.VarAttribute{6}.Role='ancillary';
187        Data.VarAttribute{7}.Role='errorflag';
188
189%% get timing from the ImaDoc file or input video
190if iview_A~=0
191    XmlFileName=find_imadoc(RootPath_A,SubDir_A,RootFile_A,FileExt_A);
192    Time=[];
193    if ~isempty(XmlFileName)
194        XmlData=imadoc2struct(XmlFileName);
195        if isfield(XmlData,'Time')
196            Time=XmlData.Time;
197        end
198        if isfield(XmlData,'Camera')
199            if isfield(XmlData.Camera,'NbSlice')&& ~isempty(XmlData.Camera.NbSlice)
200                NbSlice_calib{iview}=XmlData.Camera.NbSlice;% Nbre of slices for Zindex in phys transform
201                if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
202                    msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
203                end
204            end
205            if isfield(XmlData.Camera,'TimeUnit')&& ~isempty(XmlData.Camera.TimeUnit)
206                TimeUnit=XmlData.Camera.TimeUnit;
207            end
208        end
209    end
210end
211
212maskoldname='';% initiate the mask name
213FileType_A='';
214FileType_B='';
215CheckOverwrite=1;%default
216if isfield(Param,'CheckOverwrite')
217    CheckOverwrite=Param.CheckOverwrite;
218end
219   Data.Civ1_ImageA=fullfile_uvmat(RootPath_A,SubDir_A,RootFile_A,FileExt_A,NomType_A,i1_series_Civ1(1),[],j1_series_Civ1(1,1));
220   Data.Civ1_ImageB=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i1_series_Civ1(1),[],j2_series_Civ1(1,1));
221    FileInfo=get_file_info(Data.Civ1_ImageA);
222        par_civ1=Param.ActionInput.Civ1;% parameters for civ1
223    par_civ1.ImageHeight=FileInfo.Height;npy=FileInfo.Height;
224    par_civ1.ImageWidth=FileInfo.Width;npx=FileInfo.Width;
225SearchRange_z=floor(Param.ActionInput.Civ1.SearchBoxSize(3)/2);
226    par_civ1.Dz=Param.ActionInput.Civ1.Dz;
227    par_civ1.ImageA=zeros(2*SearchRange_z+1,npy,npx);
228par_civ1.ImageB=zeros(2*SearchRange_z+1,npy,npx);
229
230%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
231%%%%% MAIN LOOP %%%%%%
232%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
233for ifield=1:NbField_i
234    tstart=tic;
235    time_civ1=0;
236    time_patch1=0;
237    time_civ2=0;
238    time_patch2=0;
239    if checkrun% update the waitbar in interactive mode with GUI series  (checkrun=1)
240        update_waitbar(WaitbarHandle,ifield/NbField_i)
241        if  checkrun && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
242            disp('program stopped by user')
243            break
244        end
245    end
246   
247    %indicate the values of all the global attributes in the output data
248    i1=i1_series_Civ1(ifield);
249    i2=i1;
250    if ~isempty(i2_series_Civ1)
251        i2=i2_series_Civ1(ifield);
252    end
253    j1=1;
254    if ~isempty(j1_series_Civ1)
255        j1=j1_series_Civ1(ifield);
256    end
257    j2=j1;
258    if ~isempty(j2_series_Civ1)
259        j2=j2_series_Civ1(ifield);
260    end
261
262    Data.Civ1_Time=(Time(i2+1,j2+1)+Time(i1+1,j1+1))/2;% the Time is the Time at the middle of the image pair
263    Data.Civ1_Dt=Time(i2+1,j2+1)-Time(i1+1,j1+1);
264
265    for ilist=1:length(list_param)
266        Data.(Civ1_param{4+ilist})=Param.ActionInput.Civ1.(list_param{ilist});
267    end
268   
269    Data.CivStage=1;
270    % output nc file
271    ncfile_out=fullfile_uvmat(OutputPath,Param.InputTable{1,2},Param.InputTable{1,3},Param.InputTable{1,5},...
272        NomTypeNc,i1_series_Civ1(ifield),i2_series_Civ1(ifield),j1_series_Civ1(ifield),j2_series_Civ1(ifield));
273
274    if ~CheckOverwrite && exist(ncfile_out,'file')
275        disp(['existing output file ' ncfile_out ' already exists, skip to next field'])
276        continue% skip iteration if the mode overwrite is desactivated and the result file already exists
277    end
278
279
280    %% Civ1
281    % if Civ1 computation is requested
282    if isfield (Param.ActionInput,'Civ1')
283
284        disp('civ1 started')
285
286
287        % read input images (except in mode Test where it is introduced directly in Param.ActionInput.Civ1.ImageNameA and B)
288
289        par_civ1.ImageA=zeros(2*SearchRange_z+1,npy,npx);
290        par_civ1.ImageB=zeros(2*SearchRange_z+1,npy,npx);
291
292        for islice=ceil(par_civ1.Dz/2):par_civ1.Dz:NbSlice
293            if par_civ1.Dz<2*SearchRange_z+1
294            par_civ1.ImageA=circshift(par_civ1.ImageA,-par_civ1.Dz);
295            par_civ1.ImageB=circshift(par_civ1.ImageA,-par_civ1.Dz);
296            end
297              for iz=1:par_civ1.Dz
298            ImageName_A=fullfile_uvmat(RootPath_A,SubDir_A,RootFile_A,FileExt_A,NomType_A,i1_series_Civ1(ifield),[],j1_series_Civ1(ifield,islice));
299            A= read_image(ImageName_A,FileType_A);
300            ImageName_B=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i2_series_Civ1(ifield),[],j2_series_Civ1(ifield,islice));
301            B= read_image(ImageName_B,FileType_B);
302            par_civ1.ImageA(2*SearchRange_z+2-iz,:,:) = A;
303            par_civ1.ImageB(2*SearchRange_z+2-iz,:,:) = B;
304            end
305            % caluclate velocity data (y and v in indices, reverse to y component)
306            [Data.Civ1_X(islice,:,:),Data.Civ1_Y(islice,:,:), utable, vtable,wtable, ctable, FF, result_conv, errormsg] = civ3D (par_civ1);
307            if ~isempty(errormsg)
308                disp_uvmat('ERROR',errormsg,checkrun)
309                return
310            end
311
312        end
313        % case of mask TO ADAPT
314        if par_civ1.CheckMask&&~isempty(par_civ1.Mask)
315            if isfield(par_civ1,'NbSlice')
316                [RootPath_mask,SubDir_mask,RootFile_mask,i1_mask,i2_mask,j1_mask,j2_mask,Ext_mask]=fileparts_uvmat(Param.ActionInput.Civ1.Mask);
317                i1_mask=mod(i1-1,par_civ1.NbSlice)+1;
318                maskname=fullfile_uvmat(RootPath_mask,SubDir_mask,RootFile_mask,Ext_mask,'_1',i1_mask);
319            else
320                maskname=Param.ActionInput.Civ1.Mask;
321            end
322            if strcmp(maskoldname,maskname)% mask exist, not already read in civ1
323                par_civ1.Mask=mask; %use mask already opened
324            else
325                if ~isempty(regexp(maskname,'(^http://)|(^https://)'))|| exist(maskname,'file')
326                    try
327                        par_civ1.Mask=imread(maskname);%update the mask, an store it for future use
328                    catch ME
329                        if ~isempty(ME.message)
330                            errormsg=['error reading input image: ' ME.message];
331                            disp_uvmat('ERROR',errormsg,checkrun)
332                            return
333                        end
334                    end
335                else
336                    par_civ1.Mask=[];
337                end
338                mask=par_civ1.Mask;
339                maskoldname=maskname;
340            end
341        end
342        % Data.ListVarName=[Data.ListVarName 'Civ1_Z'];
343        % Data.Civ1_X=[];Data.Civ1_Y=[];Data.Civ1_Z=[];
344        % Data.Civ1_U=[];Data.Civ1_V=[];Data.Civ1_C=[];
345        %
346        %
347        % Data.Civ1_X=[Data.Civ1_X reshape(xtable,[],1)];
348        % Data.Civ1_Y=[Data.Civ1_Y reshape(Param.Civ1.ImageHeight-ytable+1,[],1)];
349        % Data.Civ1_Z=[Data.Civ1_Z ivol*ones(numel(xtable),1)];% z=image index in image coordinates
350        % Data.Civ1_U=[Data.Civ1_U reshape(utable,[],1)];
351        % Data.Civ1_V=[Data.Civ1_V reshape(-vtable,[],1)];
352        % Data.Civ1_C=[Data.Civ1_C reshape(ctable,[],1)];
353        % Data.Civ1_FF=[Data.Civ1_FF reshape(F,[],1)];
354
355    end
356
357    %% Fix1
358    if isfield (Param.ActionInput,'Fix1')
359        disp('detect_false1 started')
360        if ~isfield (Param.ActionInput,'Civ1')% if we use existing Civ1, remove previous data beyond Civ1
361            Fix1_attr=find(strcmp('Fix1',Data.ListGlobalAttribute));
362            Data.ListGlobalAttribute(Fix1_attr)=[];
363            for ilist=1:numel(Fix1_attr)
364                Data=rmfield(Data,Data.ListGlobalAttribute{Fix1_attr(ilist)});
365            end
366        end
367        list_param=fieldnames(Param.ActionInput.Fix1)';
368        Fix1_param=regexprep(list_param,'^.+','Fix1_$0');% insert 'Fix1_' before  each string in ListFixParam
369        %indicate the values of all the global attributes in the output data
370        for ilist=1:length(list_param)
371            Data.(Fix1_param{ilist})=Param.ActionInput.Fix1.(list_param{ilist});
372        end
373        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Fix1_param];
374        Data.Civ1_FF=uint8(detect_false(Param.ActionInput.Fix1,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V,Data.Civ1_FF));
375        Data.CivStage=2;
376    end
377    %% Patch1
378    if isfield (Param.ActionInput,'Patch1')
379        disp('patch1 started')
380        tstart_patch1=tic;
381
382        % record the processing parameters of Patch1 as global attributes in the result nc file
383        list_param=fieldnames(Param.ActionInput.Patch1)';
384        list_param(strcmp('TestPatch1',list_param))=[];% remove 'TestPatch1' from the list of parameters
385        Patch1_param=regexprep(list_param,'^.+','Patch1_$0');% insert 'Patch1_' before  each parameter name
386        for ilist=1:length(list_param)
387            Data.(Patch1_param{ilist})=Param.ActionInput.Patch1.(list_param{ilist});
388        end
389        Data.CivStage=3;% record the new state of processing
390        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Patch1_param];
391
392        % list the variables to record
393        nbvar=length(Data.ListVarName);
394        Data.ListVarName=[Data.ListVarName {'Civ1_U_smooth','Civ1_V_smooth','Civ1_SubRange','Civ1_NbCentres','Civ1_Coord_tps','Civ1_U_tps','Civ1_V_tps'}];
395        Data.VarDimName=[Data.VarDimName {'nb_vec_1','nb_vec_1',{'nb_coord','nb_bounds','nb_subdomain_1'},'nb_subdomain_1',...
396            {'nb_tps_1','nb_coord','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'}}];
397        Data.VarAttribute{nbvar+1}.Role='vector_x';
398        Data.VarAttribute{nbvar+2}.Role='vector_y';
399        Data.VarAttribute{nbvar+5}.Role='coord_tps';
400        Data.VarAttribute{nbvar+6}.Role='vector_x';
401        Data.VarAttribute{nbvar+7}.Role='vector_y';
402        Data.Civ1_U_smooth=Data.Civ1_U; % zeros(size(Data.Civ1_X));
403        Data.Civ1_V_smooth=Data.Civ1_V; %zeros(size(Data.Civ1_X));
404        if isfield(Data,'Civ1_FF')
405            ind_good=find(Data.Civ1_FF==0);
406        else
407            ind_good=1:numel(Data.Civ1_X);
408        end
409        if isempty(ind_good)
410            disp_uvmat('ERROR','all vectors of civ1 are bad, check input parameters' ,checkrun)
411            return
412        end
413
414        % perform Patch calculation using the UVMAT fct 'filter_tps'
415
416        [Data.Civ1_SubRange,Data.Civ1_NbCentres,Data.Civ1_Coord_tps,Data.Civ1_U_tps,Data.Civ1_V_tps,tild,Ures, Vres,tild,FFres]=...
417            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);
418        Data.Civ1_U_smooth(ind_good)=Ures;% take the interpolated (smoothed) velocity values for good vectors, keep civ1 data for the other
419        Data.Civ1_V_smooth(ind_good)=Vres;
420        Data.Civ1_FF(ind_good)=uint8(FFres);
421        time_patch1=toc(tstart_patch1);
422        disp('patch1 performed')
423    end
424
425    %% Civ2
426    if isfield (Param.ActionInput,'Civ2')
427        disp('civ2 started')
428        tstart_civ2=tic;
429        par_civ2=Param.ActionInput.Civ2;
430        % read input images
431        par_civ2.ImageA=[];
432        par_civ2.ImageB=[];
433        if strcmp(Param.ActionInput.ListCompareMode,'displacement')
434            ImageName_A_Civ2=Param.ActionInput.RefFile;
435        else
436            ImageName_A_Civ2=fullfile_uvmat(RootPath_A,SubDir_A,RootFile_A,FileExt_A,NomType_A,i1_civ2,[],j1_civ2);
437        end
438        if strcmp(ImageName_A_Civ2,ImageName_A) && isequal(FrameIndex_A_Civ1(ifield),FrameIndex_A_Civ2(ifield))
439            par_civ2.ImageA=par_civ1.ImageA;
440        else
441            [par_civ2.ImageA,VideoObject_A] = read_image(ImageName_A_Civ2,FileType_A,VideoObject_A,FrameIndex_A_Civ2(ifield));
442        end
443        ImageName_B_Civ2=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i2_civ2,[],j2_civ2);
444        if strcmp(ImageName_B_Civ2,ImageName_B) && isequal(FrameIndex_B_Civ1(ifield),FrameIndex_B_Civ2)
445            par_civ2.ImageB=par_civ1.ImageB;
446        else
447            [par_civ2.ImageB,VideoObject_B] = read_image(ImageName_B_Civ2,FileType_B,VideoObject_B,FrameIndex_B_Civ2(ifield));
448        end
449        [FileInfo_A,VideoObject_A]=get_file_info(ImageName_A_Civ2);
450        par_civ2.ImageWidth=FileInfo_A.Width;
451        par_civ2.ImageHeight=FileInfo_A.Height;
452        if isfield(par_civ2,'Grid')% grid points set as input file
453            if ischar(par_civ2.Grid)%read the grid file if the input is a file name
454                par_civ2.Grid=dlmread(par_civ2.Grid);
455                par_civ2.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
456            end
457        else% automatic grid
458            minix=floor(par_civ2.Dx/2)-0.5;
459            maxix=minix+par_civ2.Dx*floor((par_civ2.ImageWidth-1)/par_civ2.Dx);
460            miniy=floor(par_civ2.Dy/2)-0.5;
461            maxiy=minix+par_civ2.Dy*floor((par_civ2.ImageHeight-1)/par_civ2.Dy);
462            [GridX,GridY]=meshgrid(minix:par_civ2.Dx:maxix,miniy:par_civ2.Dy:maxiy);
463            par_civ2.Grid(:,1)=reshape(GridX,[],1);
464            par_civ2.Grid(:,2)=reshape(GridY,[],1);
465        end
466        % end
467
468        % get the guess from patch1 or patch2 (case 'CheckCiv3')
469
470        if isfield (par_civ2,'CheckCiv3') && par_civ2.CheckCiv3 %get the guess from  patch2
471            SubRange= Data.Civ2_SubRange;
472            NbCentres=Data.Civ2_NbCentres;
473            Coord_tps=Data.Civ2_Coord_tps;
474            U_tps=Data.Civ2_U_tps;
475            V_tps=Data.Civ2_V_tps;
476            CivStage=Data.CivStage;%store the current CivStage
477            Civ1_Dt=Data.Civ2_Dt;
478            Data=[];%reinitialise the result structure Data
479            Data.ListGlobalAttribute={'Conventions','Program','CivStage'};
480            Data.Conventions='uvmat/civdata';% states the conventions used for the description of field variables and attributes
481            Data.Program='civ_series';
482            Data.CivStage=CivStage+1;%update the current civStage after reinitialisation of Data
483            Data.ListVarName={};
484            Data.VarDimName={};
485        else % get the guess from patch1
486            SubRange= Data.Civ1_SubRange;
487            NbCentres=Data.Civ1_NbCentres;
488            Coord_tps=Data.Civ1_Coord_tps;
489            U_tps=Data.Civ1_U_tps;
490            V_tps=Data.Civ1_V_tps;
491            Civ1_Dt=Data.Civ1_Dt;
492            Data.CivStage=4;
493        end
494        % else
495        %     SubRange= par_civ2.Civ1_SubRange;
496        %     NbCentres=par_civ2.Civ1_NbCentres;
497        %     Coord_tps=par_civ2.Civ1_Coord_tps;
498        %     U_tps=par_civ2.Civ1_U_tps;
499        %     V_tps=par_civ2.Civ1_V_tps;
500        %     Civ1_Dt=par_civ2.Civ1_Dt;
501        %     Civ2_Dt=par_civ2.Civ1_Dt;
502        %     Data.ListVarName={};
503        %     Data.VarDimName={};
504        % end
505        Shiftx=zeros(size(par_civ2.Grid,1),1);% shift expected from civ1 data
506        Shifty=zeros(size(par_civ2.Grid,1),1);
507        nbval=zeros(size(par_civ2.Grid,1),1);% nbre of interpolated values at each grid point (from the different patch subdomains)
508        if par_civ2.CheckDeformation
509            DUDX=zeros(size(par_civ2.Grid,1),1);
510            DUDY=zeros(size(par_civ2.Grid,1),1);
511            DVDX=zeros(size(par_civ2.Grid,1),1);
512            DVDY=zeros(size(par_civ2.Grid,1),1);
513        end
514        NbSubDomain=size(SubRange,3);
515        for isub=1:NbSubDomain% for each sub-domain of Patch1
516            nbvec_sub=NbCentres(isub);% nbre of Civ vectors in the subdomain
517            ind_sel=find(par_civ2.Grid(:,1)>=SubRange(1,1,isub) & par_civ2.Grid(:,1)<=SubRange(1,2,isub) &...
518                par_civ2.Grid(:,2)>=SubRange(2,1,isub) & par_civ2.Grid(:,2)<=SubRange(2,2,isub));% grid points in the subdomain
519            if ~isempty(ind_sel)
520                epoints = par_civ2.Grid(ind_sel,:);% coordinates of interpolation sites (measurement grids)
521                ctrs=Coord_tps(1:nbvec_sub,:,isub) ;%(=initial points) ctrs
522                nbval(ind_sel)=nbval(ind_sel)+1;% records the number of values for each interpolation point (in case of subdomain overlap)
523                EM = tps_eval(epoints,ctrs);% thin plate spline (tps) coefficient
524                Shiftx(ind_sel)=Shiftx(ind_sel)+EM*U_tps(1:nbvec_sub+3,isub);%velocity shift estimated by tps from civ1
525                Shifty(ind_sel)=Shifty(ind_sel)+EM*V_tps(1:nbvec_sub+3,isub);
526                if par_civ2.CheckDeformation
527                    [EMDX,EMDY] = tps_eval_dxy(epoints,ctrs);%2D matrix of distances between extrapolation points epoints and spline centres (=site points) ctrs
528                    DUDX(ind_sel)=DUDX(ind_sel)+EMDX*U_tps(1:nbvec_sub+3,isub);
529                    DUDY(ind_sel)=DUDY(ind_sel)+EMDY*U_tps(1:nbvec_sub+3,isub);
530                    DVDX(ind_sel)=DVDX(ind_sel)+EMDX*V_tps(1:nbvec_sub+3,isub);
531                    DVDY(ind_sel)=DVDY(ind_sel)+EMDY*V_tps(1:nbvec_sub+3,isub);
532                end
533            end
534        end
535        if par_civ2.CheckMask&&~isempty(par_civ2.Mask)
536            if isfield(par_civ2,'NbSlice')
537                [RootPath_mask,SubDir_mask,RootFile_mask,i1_mask,i2_mask,j1_mask,j2_mask,Ext_mask]=fileparts_uvmat(Param.ActionInput.Civ2.Mask);
538                i1_mask=mod(i1-1,par_civ2.NbSlice)+1;
539                maskname=fullfile_uvmat(RootPath_mask,SubDir_mask,RootFile_mask,Ext_mask,'_1',i1_mask);
540            else
541                maskname=Param.ActionInput.Civ2.Mask;
542            end
543            if strcmp(maskoldname,maskname)% mask exist, not already read in civ1
544                par_civ2.Mask=mask; %use mask already opened
545            else
546                if exist(maskname,'file')
547                    try
548                        par_civ2.Mask=imread(maskname);%update the mask, an store it for future use
549                    catch ME
550                        if ~isempty(ME.message)
551                            errormsg=['error reading input image: ' ME.message];
552                            disp_uvmat('ERROR',errormsg,checkrun)
553                            return
554                        end
555                    end
556                else
557                    par_civ2.Mask=[];
558                end
559                mask=par_civ2.Mask;
560                maskoldname=maskname;
561            end
562        end
563
564
565        if strcmp(Param.ActionInput.ListCompareMode,'displacement')
566            Civ1_Dt=1;
567            Civ2_Dt=1;
568        else
569            Civ2_Dt=Time(i2_civ2+1,j2_civ2+1)-Time(i1_civ2+1,j1_civ2+1);
570        end
571
572        par_civ2.SearchBoxShift=(Civ2_Dt/Civ1_Dt)*[Shiftx(nbval>=1)./nbval(nbval>=1) Shifty(nbval>=1)./nbval(nbval>=1)];
573        % shift the grid points by half the expected shift to provide the correlation box position in image A
574        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];
575        if par_civ2.CheckDeformation
576            par_civ2.DUDX=DUDX(nbval>=1)./nbval(nbval>=1);
577            par_civ2.DUDY=DUDY(nbval>=1)./nbval(nbval>=1);
578            par_civ2.DVDX=DVDX(nbval>=1)./nbval(nbval>=1);
579            par_civ2.DVDY=DVDY(nbval>=1)./nbval(nbval>=1);
580        end
581
582        % calculate velocity data (y and v in image indices, reverse to y component)
583
584        [xtable, ytable, utable, vtable, ctable, F,result_conv,errormsg] = civ (par_civ2);
585
586        list_param=(fieldnames(Param.ActionInput.Civ2))';
587        list_param(strcmp('TestCiv2',list_param))=[];% remove the parameter TestCiv2 from the list
588        Civ2_param=regexprep(list_param,'^.+','Civ2_$0');% insert 'Civ2_' before  each string in list_param
589        Civ2_param=[{'Civ2_ImageA','Civ2_ImageB','Civ2_Time','Civ2_Dt'} Civ2_param]; %insert the names of the two input images
590        %indicate the values of all the global attributes in the output data
591        if exist('ImageName_A','var')
592            Data.Civ2_ImageA=ImageName_A;
593            Data.Civ2_ImageB=ImageName_B;
594            if strcmp(Param.ActionInput.ListCompareMode,'displacement')
595                Data.Civ2_Time=Time(i2_civ2+1,j2_civ2+1);% the Time is the Time of the secodn image
596                Data.Civ2_Dt=1;% Time interval is 1, to yield displacement instead of velocity=displacement/Dt at reading
597            else
598                Data.Civ2_Time=(Time(i2_civ2+1,j2_civ2+1)+Time(i1_civ2+1,j1_civ2+1))/2;
599                Data.Civ2_Dt=Civ2_Dt;
600            end
601        end
602        for ilist=1:length(list_param)
603            Data.(Civ2_param{4+ilist})=Param.ActionInput.Civ2.(list_param{ilist});
604        end
605        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ2_param];
606
607        nbvar=numel(Data.ListVarName);
608        % define the Civ2 variable (if Civ2 data are not replaced from previous calculation)
609        if isempty(find(strcmp('Civ2_X',Data.ListVarName),1))
610            Data.ListVarName=[Data.ListVarName {'Civ2_X','Civ2_Y','Civ2_U','Civ2_V','Civ2_C','Civ2_FF'}];%  cell array containing the names of the fields to record
611            Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2'}];
612            Data.VarAttribute{nbvar+1}.Role='coord_x';
613            Data.VarAttribute{nbvar+2}.Role='coord_y';
614            Data.VarAttribute{nbvar+3}.Role='vector_x';
615            Data.VarAttribute{nbvar+4}.Role='vector_y';
616            Data.VarAttribute{nbvar+5}.Role='ancillary';
617            Data.VarAttribute{nbvar+6}.Role='errorflag';
618        end
619        Data.Civ2_X=reshape(xtable,[],1);
620        Data.Civ2_Y=reshape(size(par_civ2.ImageA,1)-ytable+1,[],1);
621        Data.Civ2_U=reshape(utable,[],1);
622        Data.Civ2_V=reshape(-vtable,[],1);
623        Data.Civ2_C=reshape(ctable,[],1);
624        Data.Civ2_FF=reshape(F,[],1);
625        disp('civ2 performed')
626        time_civ2=toc(tstart_civ2);
627    elseif ~isfield(Data,'ListVarName') % we start there, using existing Civ2 data
628        if exist('ncfile','var')
629            CivFile=ncfile;
630            [Data,tild,tild,errormsg]=nc2struct(CivFile);%read civ1 and detect_false1 data in the existing netcdf file
631            if ~isempty(errormsg)
632                disp_uvmat('ERROR',errormsg,checkrun)
633                return
634            end
635            %         elseif isfield(Param,'Civ2_X')% use Civ2 data as input in Param (test mode)
636            %             Data.ListGlobalAttribute={};
637            %             Data.ListVarName={};
638            %             Data.VarDimName={};
639            %             Data.Civ2_X=Param.Civ2_X;
640            %             Data.Civ2_Y=Param.Civ2_Y;
641            %             Data.Civ2_U=Param.Civ2_U;
642            %             Data.Civ2_V=Param.Civ2_V;
643            %             Data.Civ2_FF=Param.Civ2_FF;
644        end
645    end
646
647    %% Fix2
648    if isfield (Param.ActionInput,'Fix2')
649        disp('detect_false2 started')
650        list_param=fieldnames(Param.ActionInput.Fix2)';
651        Fix2_param=regexprep(list_param,'^.+','Fix2_$0');% insert 'Fix1_' before  each string in ListFixParam
652        %indicate the values of all the global attributes in the output data
653        for ilist=1:length(list_param)
654            Data.(Fix2_param{ilist})=Param.ActionInput.Fix2.(list_param{ilist});
655        end
656        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Fix2_param];
657        Data.Civ2_FF=double(detect_false(Param.ActionInput.Fix2,Data.Civ2_C,Data.Civ2_U,Data.Civ2_V,Data.Civ2_FF));
658        Data.CivStage=Data.CivStage+1;
659    end
660
661    %% Patch2
662    if isfield (Param.ActionInput,'Patch2')
663        disp('patch2 started')
664        tstart_patch2=tic;
665        list_param=fieldnames(Param.ActionInput.Patch2)';
666        list_param(strcmp('TestPatch2',list_param))=[];% remove the parameter TestCiv1 from the list
667        Patch2_param=regexprep(list_param,'^.+','Patch2_$0');% insert 'Fix1_' before  each string in ListFixParam
668        %indicate the values of all the global attributes in the output data
669        for ilist=1:length(list_param)
670            Data.(Patch2_param{ilist})=Param.ActionInput.Patch2.(list_param{ilist});
671        end
672        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Patch2_param];
673
674        nbvar=length(Data.ListVarName);
675        Data.ListVarName=[Data.ListVarName {'Civ2_U_smooth','Civ2_V_smooth','Civ2_SubRange','Civ2_NbCentres','Civ2_Coord_tps','Civ2_U_tps','Civ2_V_tps'}];
676        Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2',{'nb_coord','nb_bounds','nb_subdomain_2'},{'nb_subdomain_2'},...
677            {'nb_tps_2','nb_coord','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'}}];
678
679        Data.VarAttribute{nbvar+1}.Role='vector_x';
680        Data.VarAttribute{nbvar+2}.Role='vector_y';
681        Data.VarAttribute{nbvar+5}.Role='coord_tps';
682        Data.VarAttribute{nbvar+6}.Role='vector_x';
683        Data.VarAttribute{nbvar+7}.Role='vector_y';
684        Data.Civ2_U_smooth=Data.Civ2_U;
685        Data.Civ2_V_smooth=Data.Civ2_V;
686        if isfield(Data,'Civ2_FF')
687            ind_good=find(Data.Civ2_FF==0);
688        else
689            ind_good=1:numel(Data.Civ2_X);
690        end
691        if isempty(ind_good)
692            disp_uvmat('ERROR','all vectors of civ2 are bad, check input parameters' ,checkrun)
693            return
694        end
695
696        [Data.Civ2_SubRange,Data.Civ2_NbCentres,Data.Civ2_Coord_tps,Data.Civ2_U_tps,Data.Civ2_V_tps,tild,Ures,Vres,tild,FFres]=...
697            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);
698        Data.Civ2_U_smooth(ind_good)=Ures;
699        Data.Civ2_V_smooth(ind_good)=Vres;
700        Data.Civ2_FF(ind_good)=FFres;
701        Data.CivStage=Data.CivStage+1;
702        time_patch2=toc(tstart_patch2);
703        disp('patch2 performed')
704    end
705
706    %% write result in a netcdf file if requested
707    % if CheckOutputFile
708    errormsg=struct2nc(ncfile_out,Data);
709    if isempty(errormsg)
710        disp([ncfile_out ' written'])
711        %[success,msg] = fileattrib(ncfile_out ,'+w','g');% done in struct2nc
712    else
713        disp(errormsg)
714    end
715    time_total=toc(tstart);
716    disp(['ellapsed time ' num2str(time_total/60,2) ' minutes'])
717    disp(['time image reading ' num2str(time_input,2) ' s'])
718    disp(['time civ1 ' num2str(time_civ1,2) ' s'])
719    disp(['time patch1 ' num2str(time_patch1,2) ' s'])
720    disp(['time civ2 ' num2str(time_civ2,2) ' s'])
721    disp(['time patch2 ' num2str(time_patch2,2) ' s'])
722    disp(['time other ' num2str((time_total-time_input-time_civ1-time_patch1-time_civ2-time_patch2),2) ' s'])
723    % end
724end
725
726
727% 'civ': function piv.m adapted from PIVlab http://pivlab.blogspot.com/
728%--------------------------------------------------------------------------
729% function [xtable ytable utable vtable typevector] = civ (image1,image2,ibx,iby step, subpixfinder, mask, roi)
730%
731% OUTPUT:
732% xtable: set of x coordinates
733% ytable: set of y coordiantes
734% utable: set of u displacements (along x)
735% vtable: set of v displacements (along y)
736% ctable: max image correlation for each vector
737% typevector: set of flags, =1 for good, =0 for NaN vectors
738%
739%INPUT:
740% par_civ: structure of input parameters, with fields:
741%  .ImageA: first image for correlation (matrix)
742%  .ImageB: second image for correlation(matrix)
743%  .CorrBoxSize: 1,2 vector giving the size of the correlation box in x and y
744%  .SearchBoxSize:  1,2 vector giving the size of the search box in x and y
745%  .SearchBoxShift: 1,2 vector or 2 column matrix (for civ2) giving the shift of the search box in x and y
746%  .CorrSmooth: =1 or 2 determines the choice of the sub-pixel determination of the correlation max
747%  .ImageWidth: nb of pixels of the image in x
748%  .Dx, Dy: mesh for the PIV calculation
749%  .Grid: grid giving the PIV calculation points (alternative to .Dx .Dy): centres of the correlation boxes in Image A
750%  .Mask: name of a mask file or mask image matrix itself
751%  .MinIma: thresholds for image luminosity
752%  .MaxIma
753%  .CheckDeformation=1 for subpixel interpolation and image deformation (linear transform)
754%  .DUDX: matrix of deformation obtained from patch at each grid point
755%  .DUDY
756%  .DVDX:
757%  .DVDY
758
759function [xtable,ytable,utable,vtable,wtable,ctable,FF,result_conv,errormsg] = civ3D (par_civ)
760
761%% prepare measurement grid
762
763minix=floor(par_civ.Dx/2)-0.5;
764maxix=minix+par_civ.Dx*floor((par_civ.ImageWidth-1)/par_civ.Dx);
765miniy=floor(par_civ.Dy/2)-0.5;% first automatic grid point at half the mesh Dy
766maxiy=miniy+par_civ.Dy*floor((par_civ.ImageHeight-1)/par_civ.Dy);
767[GridX,GridY]=meshgrid(minix:par_civ.Dx:maxix,miniy:par_civ.Dy:maxiy);
768par_civ.Grid(:,:,1)=GridX;
769par_civ.Grid(:,:,2)=GridY;% increases with array index,
770[nbvec_y,nbvec_x,~]=size(par_civ.Grid);
771%
772%
773% minix=floor(par_civ.Dx/2)-0.5;
774%     maxix=minix+par_civ.Dx*floor((par_civ.ImageWidth-1)/par_civ.Dx);
775%     miniy=floor(par_civ.Dy/2)-0.5;% first automatic grid point at half the mesh Dy
776%     maxiy=miniy+par_civ.Dy*floor((par_civ.ImageHeight-1)/par_civ.Dy);
777%     [GridX,GridY]=meshgrid(minix:par_civ.Dx:maxix,miniy:par_civ.Dy:maxiy);
778%     par_civ.Grid(:,1)=reshape(GridX,[],1);
779%     par_civ.Grid(:,2)=reshape(GridY,[],1);% increases with array index
780
781%% prepare correlation and search boxes
782ibx2=floor(par_civ.CorrBoxSize(1)/2);
783iby2=floor(par_civ.CorrBoxSize(2)/2);
784isx2=floor(par_civ.SearchBoxSize(1)/2);
785isy2=floor(par_civ.SearchBoxSize(2)/2);
786isz2=floor(par_civ.SearchBoxSize(3)/2);
787kref=isz2+1;%middle index of the z slice
788shiftx=round(par_civ.SearchBoxShift(:,1));%use the input shift estimate, rounded to the next integer value
789shifty=-round(par_civ.SearchBoxShift(:,2));% sign minus because image j index increases when y decreases
790if numel(shiftx)==1% case of a unique shift for the whole field( civ1)
791    shiftx=shiftx*ones(nbvec_y,nbvec_x,1);
792    shifty=shifty*ones(nbvec_y,nbvec_x,1);
793end
794
795%% Array initialisation and default output  if par_civ.CorrSmooth=0 (just the grid calculated, no civ computation)
796xtable=round(par_civ.Grid(:,:,1)+0.5)-0.5;
797ytable=round(par_civ.ImageHeight-par_civ.Grid(:,:,2)+0.5)-0.5;% y index corresponding to the position in image coordiantes
798utable=shiftx;%zeros(nbvec,1);
799vtable=shifty;%zeros(nbvec,1);
800wtable=zeros(size(utable));
801ctable=zeros(nbvec_y,nbvec_x,1);
802FF=zeros(nbvec_y,nbvec_x,1);
803result_conv=[];
804errormsg='';
805
806%% prepare mask
807check_MinIma=isfield(par_civ,'MinIma');% test for image luminosity threshold
808check_MaxIma=isfield(par_civ,'MaxIma') && ~isempty(par_civ.MaxIma);
809
810[npz,npy_ima,npx_ima]=size(par_civ.ImageA);
811if ~isequal(size(par_civ.ImageB),[npz npy_ima npx_ima])
812    errormsg='image pair with unequal size';
813    return
814end
815
816%% Apply mask
817% Convention for mask, IDEAS NOT IMPLEMENTED
818% mask >200 : velocity calculated
819%  200 >=mask>150;velocity not calculated, interpolation allowed (bad spots)
820% 150>=mask >100: velocity not calculated, nor interpolated
821%  100>=mask> 20: velocity not calculated, impermeable (no flux through mask boundaries)
822%  20>=mask: velocity=0
823checkmask=0;
824MinA=min(min(min(par_civ.ImageA)));
825%MinB=min(min(par_civ.ImageB));
826%check_undefined=false(size(par_civ.ImageA));
827if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
828    checkmask=1;
829    if ~isequal(size(par_civ.Mask),[npy_ima npx_ima])
830        errormsg='mask must be an image with the same size as the images';
831        return
832    end
833    check_undefined=(par_civ.Mask<200 & par_civ.Mask>=20 );
834end
835
836%% compute image correlations: MAINLOOP on velocity vectors
837corrmax=0;
838sum_square=1;% default
839mesh=1;% default
840CheckDeformation=isfield(par_civ,'CheckDeformation')&& par_civ.CheckDeformation==1;
841if CheckDeformation
842    mesh=0.25;%mesh in pixels for subpixel image interpolation (x 4 in each direction)
843    par_civ.CorrSmooth=2;% use SUBPIX2DGAUSS (take into account more points near the max)
844end
845
846if par_civ.CorrSmooth~=0 % par_civ.CorrSmooth=0 implies no civ computation (just input image and grid points given)
847    for ivec_x=1:nbvec_x
848        for ivec_y=1:nbvec_y
849            ivec_y
850            iref=round(par_civ.Grid(ivec_y,ivec_x,1)+0.5)% xindex on the image A for the middle of the correlation box
851            jref=round(par_civ.ImageHeight-par_civ.Grid(ivec_y,ivec_x,2)+0.5)%  j index  for the middle of the correlation box in the image A
852            subrange1_x=iref-ibx2:iref+ibx2;% x indices defining the first subimage
853            subrange1_y=jref-iby2:jref+iby2;% y indices defining the first subimage
854            subrange2_x=iref+shiftx(ivec_y,ivec_x)-isx2:iref+shiftx(ivec_y,ivec_x)+isx2;%x indices defining the second subimage
855            subrange2_y=jref+shifty(ivec_y,ivec_x)-isy2:jref+shifty(ivec_y,ivec_x)+isy2;%y indices defining the second subimage
856            image1_crop=MinA*ones(npz,numel(subrange1_y),numel(subrange1_x));% default value=min of image A
857            image2_crop=MinA*ones(npz,numel(subrange2_y),numel(subrange2_x));% default value=min of image A
858            check1_x=subrange1_x>=1 & subrange1_x<=par_civ.ImageWidth;% check which points in the subimage 1 are contained in the initial image 1
859            check1_y=subrange1_y>=1 & subrange1_y<=par_civ.ImageHeight;
860            check2_x=subrange2_x>=1 & subrange2_x<=par_civ.ImageWidth;% check which points in the subimage 2 are contained in the initial image 2
861            check2_y=subrange2_y>=1 & subrange2_y<=par_civ.ImageHeight;
862            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
863            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
864            if checkmask
865                mask1_crop=ones(numel(subrange1_y),numel(subrange1_x));% default value=1 for mask
866                mask2_crop=ones(numel(subrange2_y),numel(subrange2_x));% default value=1 for mask
867                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
868                mask2_crop(check2_y,check2_x)=check_undefined(subrange2_y(check2_y),subrange2_x(check2_x));%extract a mask subimage (search box) from image B
869                sizemask=sum(sum(mask1_crop))/(numel(subrange1_y)*numel(subrange1_x));%size of the masked part relative to the correlation sub-image
870                if sizemask > 1/2% eliminate point if more than half of the correlation box is masked
871                    FF(ivec_y,ivec_x)=1; %
872                    utable(ivec_y,ivec_x)=NaN;
873                    vtable(ivec_y,ivec_x)=NaN;
874                else
875                    FF(ivec_y,ivec_x)=0;
876                    image1_crop=image1_crop.*~mask1_crop;% put to zero the masked pixels (mask1_crop='true'=1)
877                    image2_crop=image2_crop.*~mask2_crop;
878                    image1_mean=mean(mean(image1_crop))/(1-sizemask);
879                    image2_mean=mean(mean(image2_crop))/(1-sizemask);
880                end
881            else
882                image1_mean=mean(mean(image1_crop));
883                image2_mean=mean(mean(image2_crop));
884            end
885            %threshold on image minimum
886            if FF(ivec_y,ivec_x)==0
887                if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
888                    FF(ivec_y,ivec_x)=1;
889                    %threshold on image maximum
890                elseif check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
891                    FF(ivec_y,ivec_x)=1;
892                end
893                if FF(ivec_y,ivec_x)==1
894                    utable(ivec_y,ivec_x)=NaN;
895                    vtable(ivec_y,ivec_x)=NaN;
896                else
897                    %mask
898                    if checkmask
899                        image1_crop=(image1_crop-image1_mean).*~mask1_crop;%substract the mean, put to zero the masked parts
900                        image2_crop=(image2_crop-image2_mean).*~mask2_crop;
901                    else
902                        image1_crop=(image1_crop-image1_mean);
903                        image2_crop=(image2_crop-image2_mean);
904                    end
905
906               
907                    %reference: Oliver Pust, PIV: Direct Cross-Correlation
908                    for kz=1:par_civ.SearchBoxSize(3)
909                        subima2=squeeze(image2_crop(kz,:,:));
910                        subima1=squeeze(image1_crop(kref,:,:));
911                        correl_xy=conv2(subima2,flip(flip(subima1,2),1),'valid');
912                          result_conv(kz,:,:)= correl_xy;
913                        max_xy(kz)=max(max(correl_xy));
914                    [xk(kz),yk(kz)]=find(correl_xy==max_xy(kz),1);
915               
916                    end
917                    [corrmax,z]=max(max_xy);
918               
919                    x=xk(z);
920                    y=yk(z);
921                    result_conv=(result_conv/corrmax)*255; %normalize, peak=always 255
922                    subimage2_crop=squeeze(image2_crop(z,y:y+2*iby2/mesh,x:x+2*ibx2/mesh));%subimage of image 2 corresponding to the optimum displacement of first image
923                    sum_square=sum(sum(squeeze(image1_crop(z,:,:).*image1_crop(z,:,:))));
924                    sum_square=sum_square*sum(sum(subimage2_crop.*subimage2_crop));% product of variances of image 1 and 2
925                    sum_square=sqrt(sum_square);% srt of the variance product to normalise correlation
926                    if ~isempty(y) && ~isempty(x)
927       
928                            if par_civ.CorrSmooth==1
929                                [vector,FF(ivec_y,ivec_x)] = SUBPIXGAUSS (result_conv(z,:,:),x,y);%TODO: improve by max optimisation along z
930                            elseif par_civ.CorrSmooth==2
931                                [vector,FF(ivec_y,ivec_x)] = SUBPIX2DGAUSS (result_conv(z,:,:),x,y);
932                            else
933                                [vector,FF(ivec_y,ivec_x)] = quadr_fit(result_conv(z,:,:),x,y);
934                            end
935                            utable(ivec_y,ivec_x)=vector(1)*mesh+shiftx(ivec_y,ivec_x);
936                            vtable(ivec_y,ivec_x)=vector(2)*mesh+shifty(ivec_y,ivec_x);
937                            xtable(ivec_y,ivec_x)=iref+utable(ivec_y,ivec_x)/2-0.5;% convec flow (velocity taken at the point middle from imgae 1 and 2)
938                            ytable(ivec_y,ivec_x)=jref+vtable(ivec_y,ivec_x)/2-0.5;% and position of pixel 1=0.5 (convention for image coordinates=0 at the edge)
939                            iref=round(xtable(ivec_y,ivec_x)+0.5);% nearest image index for the middle of the vector
940                            jref=round(ytable(ivec_y,ivec_x)+0.5);
941                            wtable(ivec_y,ivec_x)=z-kref;
942                            % eliminate vectors located in the mask
943                            if  checkmask && (iref<1 || jref<1 ||iref>npx_ima || jref>npy_ima ||( par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100))
944                                utable(ivec_y,ivec_x)=0;
945                                vtable(ivec_y,ivec_x)=0;
946                                FF(ivec_y,ivec_x)=1;
947                            end
948                            ctable(ivec_y,ivec_x)=corrmax/sum_square;% correlation value
949
950                    else
951                        FF(ivec_y,ivec_x)=1;
952                    end
953                end
954            end
955        end
956    end
957end
958result_conv=result_conv*corrmax/(255*sum_square);% keep the last correlation matrix for output
959
960%------------------------------------------------------------------------
961% --- Find the maximum of the correlation function after interpolation
962% OUPUT:
963% vector = optimum displacement vector with subpixel correction
964% F =flag: =0 OK
965%           =-2 , warning: max too close to the edge of the search box (1 pixel margin)
966% INPUT:
967% x,y: position of the maximum correlation at integer values
968
969function [vector,F] = SUBPIXGAUSS (result_conv,x,y)
970%------------------------------------------------------------------------
971% vector=[0 0]; %default
972F=0;
973[npy,npx]=size(result_conv);
974result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1  (=0 by discretisation, to avoid divergence in the log)
975%the following 8 lines are copyright (c) 1998, Uri Shavit, Roi Gurka, Alex Liberzon, Technion ??? Israel Institute of Technology
976%http://urapiv.wordpress.com
977peaky = y;
978if y < npy && y > 1
979    f0 = log(result_conv(y,x));
980    f1 = log(result_conv(y-1,x));
981    f2 = log(result_conv(y+1,x));
982    peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
983else
984    F=1; % warning flag for vector truncated by the limited search box
985end
986peakx=x;
987if x < npx-1 && x > 1
988    f0 = log(result_conv(y,x));
989    f1 = log(result_conv(y,x-1));
990    f2 = log(result_conv(y,x+1));
991    peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
992else
993    F=1; % warning flag for vector truncated by the limited search box
994end
995vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
996
997%------------------------------------------------------------------------
998% --- Find the maximum of the correlation function after interpolation
999function [vector,F] = SUBPIX2DGAUSS (result_conv,x,y)
1000%------------------------------------------------------------------------
1001% vector=[0 0]; %default
1002F=1;
1003peaky=y;
1004peakx=x;
1005result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1 (to avoid divergence in the log)
1006[npy,npx]=size(result_conv);
1007if (x < npx) && (y < npy) && (x > 1) && (y > 1)
1008    F=0;
1009    for i=-1:1
1010        for j=-1:1
1011            %following 15 lines based on
1012            %H. Nobach ??? M. Honkanen (2005)
1013            %Two-dimensional Gaussian regression for sub-pixel displacement
1014            %estimation in particle image velocimetry or particle position
1015            %estimation in particle tracking velocimetry
1016            %Experiments in Fluids (2005) 38: 511???515
1017            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
1018            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
1019            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
1020            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
1021            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
1022        end
1023    end
1024    c10=(1/6)*sum(sum(c10));
1025    c01=(1/6)*sum(sum(c01));
1026    c11=(1/4)*sum(sum(c11));
1027    c20=(1/6)*sum(sum(c20));
1028    c02=(1/6)*sum(sum(c02));
1029    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11^2);
1030    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11^2);
1031    if abs(deltax)<1
1032        peakx=x+deltax;
1033    end
1034    if abs(deltay)<1
1035        peaky=y+deltay;
1036    end
1037end
1038vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
1039
1040%------------------------------------------------------------------------
1041% --- Find the maximum of the correlation function after quadratic interpolation
1042function [vector,F] = quadr_fit(result_conv,x,y)
1043[npy,npx]=size(result_conv);
1044if x<4 || y<4 || npx-x<4 ||npy-y <4
1045    F=1;
1046    vector=[x y];
1047else
1048    F=0;
1049    x_ind=x-4:x+4;
1050    y_ind=y-4:y+4;
1051    x_vec=0.25*(x_ind-x);
1052    y_vec=0.25*(y_ind-y);
1053    [X,Y]=meshgrid(x_vec,y_vec);
1054    coord=[reshape(X,[],1) reshape(Y,[],1)];
1055    result_conv=reshape(result_conv(y_ind,x_ind),[],1);
1056   
1057   
1058    % n=numel(X);
1059    % x=[X Y];
1060    % X=X-0.5;
1061    % Y=Y+0.5;
1062    % y = (X.*X+2*Y.*Y+X.*Y+6) + 0.1*rand(n,1);
1063    p = polyfitn(coord,result_conv,2);
1064    A(1,1)=2*p.Coefficients(1);
1065    A(1,2)=p.Coefficients(2);
1066    A(2,1)=p.Coefficients(2);
1067    A(2,2)=2*p.Coefficients(4);
1068    vector=[x y]'-A\[p.Coefficients(3) p.Coefficients(5)]';
1069    vector=vector'-[floor(npx/2) floor(npy/2)]-1 ;
1070    % zg = polyvaln(p,coord);
1071    % figure
1072    % surf(x_vec,y_vec,reshape(zg,9,9))
1073    % hold on
1074    % plot3(X,Y,reshape(result_conv,9,9),'o')
1075    % hold off
1076end
1077
1078
1079function FF=detect_false(Param,C,U,V,FFIn)
1080FF=FFIn;%default, good vectors
1081% FF=1, for correlation max at edge, not set in this function
1082% FF=2, for too small correlation
1083% FF=3, for velocity outside bounds
1084% FF=4 for exclusion by difference with the smoothed field, not set in this function
1085
1086if isfield (Param,'MinCorr')
1087     FF(C<Param.MinCorr & FFIn==0)=2;
1088end
1089if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
1090    Umod= U.*U+V.*V;
1091    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
1092        U2Min=Param.MinVel*Param.MinVel;
1093        FF(Umod<U2Min & FFIn==0)=3;
1094    end
1095    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
1096         U2Max=Param.MaxVel*Param.MaxVel;
1097        FF(Umod>U2Max & FFIn==0)=3;
1098    end
1099end
1100
1101%------------------------------------------------------------------------
1102% --- determine the list of index pairs of processing file
1103function [i1_series,i2_series,j1_series,j2_series,check_bounds,NomTypeNc]=...
1104    find_pair_indices(str_civ,i_series,j_series,MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j)
1105%------------------------------------------------------------------------
1106i1_series=i_series;% set of first image indexes
1107i2_series=i_series;
1108j1_series=j_series;%ones(size(i_series));% set of first image numbers
1109j2_series=j_series;%ones(size(i_series));
1110r=regexp(str_civ,'^\D(?<ind>[i|j])=( -| )(?<num1>\d+)\|(?<num2>\d+)','names');
1111if ~isempty(r)
1112    mode=['D' r.ind];
1113    ind1=str2num(r.num1);
1114    ind2=str2num(r.num2);
1115else
1116    mode='j1-j2';
1117    r=regexp(str_civ,'^j= (?<num1>[a-z])-(?<num2>[a-z])','names');
1118    if ~isempty(r)
1119        NomTypeNc='_1ab';
1120    else
1121        r=regexp(str_civ,'^j= (?<num1>[A-Z])-(?<num2>[A-Z])','names');
1122        if ~isempty(r)
1123            NomTypeNc='_1AB';
1124        else
1125            r=regexp(str_civ,'^j= (?<num1>\d+)-(?<num2>\d+)','names');
1126            if ~isempty(r)
1127                NomTypeNc='_1_1-2';
1128            end
1129        end
1130    end
1131    if isempty(r)
1132        display('wrong pair mode input option')
1133    else
1134        ind1=stra2num(r.num1);
1135        ind2=stra2num(r.num2);
1136    end
1137end
1138switch mode
1139    case 'Di'
1140        i1_series=i_series-ind1;% set of first image numbers
1141        i2_series=i_series+ind2;
1142        check_bounds=i1_series<MinIndex_i | i2_series>MaxIndex_i;
1143        if isempty(j_series)
1144            NomTypeNc='_1-2';
1145        else
1146            j1_series=j_series;
1147            j2_series=j_series;
1148            NomTypeNc='_1-2_1';
1149        end
1150    case 'Dj'
1151        j1_series=j_series-ind1;
1152        j2_series=j_series+ind2;
1153        check_bounds=j1_series<MinIndex_j | j2_series>MaxIndex_j;
1154        NomTypeNc='_1_1-2';
1155    otherwise %bursts
1156        i1_series=i_series(1,:);% do not sweep the j index
1157        i2_series=i_series(1,:);
1158        j1_series=ind1*ones(1,size(i_series,2));% j index is fixed by pair choice
1159        j2_series=ind2*ones(1,size(i_series,2));
1160        check_bounds=zeros(size(i1_series));% no limitations due to min-max indices
1161end
1162
1163
1164
1165
Note: See TracBrowser for help on using the repository browser.