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

Last change on this file since 1164 was 1164, checked in by sommeria, 2 months ago

civ3D updated

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