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

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

various bugs repaired

File size: 54.7 KB
RevLine 
[1164]1%'civ_3D': 3D PIV from image scan in a volume
[1148]2
[1089]3%------------------------------------------------------------------------
[1148]4% function [Data,errormsg,result_conv]= civ_3D(Param)
[1089]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.
[1164]14%     Param.Action.RUN = 0 (to set the status of the GUI series) or =1 to RUN the computation
[1089]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
[1148]19%                      .Civ1: parameters for civ1cc
20%                      .Fix1: parameters for detect_false1
[1089]21%                      .Patch1:
22%                      .Civ2: for civ2
23%                      .Fix2:
24%                      .Patch2:
25
26%=======================================================================
[1126]27% Copyright 2008-2024, LEGI UMR 5519 / CNRS UGA G-INP, Grenoble, France
[1089]28%   http://www.legi.grenoble-inp.fr
[1127]29%   Joel.Sommeria - Joel.Sommeria (A) univ-grenoble-alpes.fr
[1089]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'))
[1164]51   
52    Data=civ_input(Param)
53   
[1089]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)
[1156]56    Data.IndexRange_j='whole';% prescribes the file index ranges j from min to max (options 'off'/'on'/'whole', 'on' by default)
[1089]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)
[1148]63    Data.OutputDirExt='.civ_3D';%set the output dir extension
[1089]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)
[1148]67    if isfield(Data,'ActionInput') && isfield(Data.ActionInput,'PairIndices') && strcmp(Data.ActionInput.PairIndices.ListPairMode,'pair j1-j2')
[1089]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
[1164]85   
86   
[1089]87    return
88end
[1148]89%% END OF ENTERING INPUT PARAMETER MODE
[1089]90
[1148]91%% RUN MODE: read input parameters from an xml file if input is a file name (batch mode)
[1089]92if ischar(Param)
93    Param=xml2struct(Param);% read Param as input file (batch case)
94    checkrun=0;
[1148]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;
[1089]101end
102
[1148]103%% test input Param
104if ~isfield(Param,'InputTable')
105    disp('ERROR: no input file entered')
106    return
107end
[1089]108if ~isfield(Param,'ActionInput')
109    disp_uvmat('ERROR','no parameter set for PIV',checkrun)
110    return
111end
112iview_A=0;%default values
113
[1148]114if isfield(Param,'OutputSubDir')&& isfield(Param,'OutputDirExt')
115    OutputDir=[Param.OutputSubDir Param.OutputDirExt];
[1164]116    OutputPath=fullfile(Param.OutputPath,num2str(Param.Experiment),num2str(Param.Device));
[1148]117else
118    disp_uvmat('ERROR','no output folder defined',checkrun)
119    return
120end
[1089]121
[1148]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
[1164]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;
[1148]144end
[1164]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};
[1089]155
[1164]156
[1148]157PairCiv1=Param.ActionInput.PairIndices.ListPairCiv1;
158
[1157]159[i1_series_Civ1,i2_series_Civ1,j1_series_Civ1,j2_series_Civ1,~,NomTypeNc]=...
[1164]160    find_pair_indices(PairCiv1,i1_series{1},j1_series{1},MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j);
161
[1148]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
[1089]169%% prepare output Data
170ListGlobalAttribute={'Conventions','Program','CivStage'};
[1157]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
[1089]176Data.CivStage=0;%default
[1164]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
[1157]184% set the list of variables
[1158]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'},...
[1157]187    {'npz','npy','npx'},{'npz','npy','npx'},{'npz','npy','npx'}};
[1158]188Data.VarAttribute{1}.Role='coord_z';
189Data.VarAttribute{2}.Role='coord_x';
[1160]190Data.VarAttribute{3}.Role='coord_y';
[1158]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';
[1163]196% Data.Coord_z=j1_series_Civ1;
[1157]197% path for output nc file
198OutputPath=fullfile(Param.OutputPath,num2str(Param.Experiment),num2str(Param.Device),[Param.OutputSubDir Param.OutputDirExt]);
[1089]199
200%% get timing from the ImaDoc file or input video
201if iview_A~=0
[1152]202    XmlFileName=find_imadoc(RootPath_A,SubDir_A);
[1089]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
[1164]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;
[1163]236SearchRange_z=Param.ActionInput.Civ1.SearchRange(3);
[1164]237par_civ1.Dz=Param.ActionInput.Civ1.Dz;
238par_civ1.ImageA=zeros(2*SearchRange_z+1,npy,npx);
[1148]239par_civ1.ImageB=zeros(2*SearchRange_z+1,npy,npx);
240
[1157]241
242
[1148]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)
[1089]254        if  checkrun && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
255            disp('program stopped by user')
256            break
257        end
258    end
[1148]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);
[1089]265    end
[1148]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   
[1164]275   
276   
[1157]277    ncfile_out=fullfile_uvmat(OutputPath,'',Param.InputTable{1,3},'.nc',...
[1164]278        '_1-1',i1_series_Civ1(ifield),i2_series_Civ1(ifield)); %output file name
279   
[1148]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
[1164]284   
285   
286%% Civ1 computation if requested
287    if Param.ActionInput.CheckCiv1
288       
[1148]289        disp('civ1 started')
[1164]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;
[1157]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
[1148]300        par_civ1.ImageB=zeros(2*SearchRange_z+1,npy,npx);
[1165]301        Data.Coord_z=(1:floor((NbSlice-SearchRange_z)/par_civ1.Dz))+SearchRange_z;%SearchRange_z+1:par_civ1.Dz:NbSlice-1;
302        z_index=1;%first vertical block centered at image index par_civ1.Dz (not SearchRange_z+1
303        for iz=1:par_civ1.Dz+SearchRange_z%2*SearchRange_z+1
[1157]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);%
[1151]306            A= read_image(ImageName_A,FileType_A);
[1157]307            ImageName_B=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i2_series_Civ1(1,ifield),[],j_image_index);
[1151]308            B= read_image(ImageName_B,FileType_B);
[1165]309            par_civ1.ImageA(iz+SearchRange_z-par_civ1.Dz+1,:,:) = A;
310            par_civ1.ImageB(iz+SearchRange_z-par_civ1.Dz+1,:,:) = B;
[1157]311        end
[1163]312       
[1148]313        % case of mask TO ADAPT
[1089]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
[1148]325                if ~isempty(regexp(maskname,'(^http://)|(^https://)'))|| exist(maskname,'file')
[1089]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
[1164]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
[1165]356                j_image_index=z_index*par_civ1.Dz+SearchRange_z-par_civ1.Dz+iz
357                if j_image_index<=size(j1_series_Civ1,1)
358%                     j_image_index=j1_series_Civ1(image_index,1)
[1164]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       
[1148]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=[];
[1164]391        %
392        %
[1148]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)];
[1164]400       
[1089]401    end
[1164]402   
403%% Fix1
[1089]404    if isfield (Param.ActionInput,'Fix1')
[1148]405        disp('detect_false1 started')
[1089]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];
[1148]420        Data.Civ1_FF=uint8(detect_false(Param.ActionInput.Fix1,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V,Data.Civ1_FF));
[1089]421        Data.CivStage=2;
422    end
[1164]423   
424%% Patch1
[1089]425    if isfield (Param.ActionInput,'Patch1')
426        disp('patch1 started')
[1148]427        tstart_patch1=tic;
[1164]428       
[1089]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];
[1164]438       
[1089]439        % list the variables to record
440        nbvar=length(Data.ListVarName);
[1163]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'}}];
[1089]443        Data.VarAttribute{nbvar+1}.Role='vector_x';
444        Data.VarAttribute{nbvar+2}.Role='vector_y';
[1164]445        Data.VarAttribute{nbvar+5}.Role='vector_z';
[1165]446       
447        [Data.ListVarName,IA]=unique(Data.ListVarName);%suppress duplicate definition of variables (in cas of patch redone from previous file)
448        Data.VarDimName=Data.VarDimName(IA);
449        Data.VarAttribute=Data.VarAttribute(IA);
[1163]450        Data.Civ1_U_smooth=Data.Civ1_U;
[1164]451        Data.Civ1_V_smooth=Data.Civ1_V;
452        Data.Civ1_W_smooth=Data.Civ1_W;
[1089]453        if isfield(Data,'Civ1_FF')
454            ind_good=find(Data.Civ1_FF==0);
455        else
[1163]456            disp_uvmat('ERROR','detection of error vectors (FIX operation) needed before PATCH' ,checkrun)
457            return
[1089]458        end
[1148]459        if isempty(ind_good)
460            disp_uvmat('ERROR','all vectors of civ1 are bad, check input parameters' ,checkrun)
461            return
462        end
[1164]463       
[1089]464        % perform Patch calculation using the UVMAT fct 'filter_tps'
[1164]465        Civ1_Z=0.5*Data.Civ1_W;
466        for iz=1:numel(Data.Coord_z)
467            Civ1_Z(iz,:,:)=Civ1_Z(iz,:,:)+Data.Coord_z(iz);   
468        end
469        [npz,npy,npx]=size(Data.Civ1_X);
[1163]470        [Data.Civ1_SubRange,Data.Civ1_NbCentres,Data.Civ1_Coord_tps,Data.Civ1_U_tps,Data.Civ1_V_tps,Data.Civ1_W_tps,...
[1164]471            Data.Civ1_U_smooth(ind_good),Data.Civ1_V_smooth(ind_good),Data.Civ1_W_smooth(ind_good),FFres]=...
[1165]472            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),...
[1164]473            Data.Patch1_SubDomainSize,Data.Patch1_FieldSmooth,Data.Patch1_MaxDiff);
474        Data.Civ1_FF(ind_good)=uint8(4*FFres);
475        Data.Civ1_FF=reshape(Data.Civ1_FF,npz,npy,npx);
476        Data.Civ1_U=reshape(Data.Civ1_U,npz,npy,npx);
477        Data.Civ1_V=reshape(Data.Civ1_V,npz,npy,npx);
478        Data.Civ1_W=reshape(Data.Civ1_W,npz,npy,npx);
[1148]479        time_patch1=toc(tstart_patch1);
[1089]480        disp('patch1 performed')
481    end
[1164]482   
[1089]483    %% Civ2
484    if isfield (Param.ActionInput,'Civ2')
485        disp('civ2 started')
[1148]486        tstart_civ2=tic;
[1089]487        par_civ2=Param.ActionInput.Civ2;
[1148]488        % read input images
489        par_civ2.ImageA=[];
490        par_civ2.ImageB=[];
491        if strcmp(Param.ActionInput.ListCompareMode,'displacement')
492            ImageName_A_Civ2=Param.ActionInput.RefFile;
493        else
[1089]494            ImageName_A_Civ2=fullfile_uvmat(RootPath_A,SubDir_A,RootFile_A,FileExt_A,NomType_A,i1_civ2,[],j1_civ2);
[1148]495        end
496        if strcmp(ImageName_A_Civ2,ImageName_A) && isequal(FrameIndex_A_Civ1(ifield),FrameIndex_A_Civ2(ifield))
497            par_civ2.ImageA=par_civ1.ImageA;
498        else
499            [par_civ2.ImageA,VideoObject_A] = read_image(ImageName_A_Civ2,FileType_A,VideoObject_A,FrameIndex_A_Civ2(ifield));
500        end
501        ImageName_B_Civ2=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i2_civ2,[],j2_civ2);
502        if strcmp(ImageName_B_Civ2,ImageName_B) && isequal(FrameIndex_B_Civ1(ifield),FrameIndex_B_Civ2)
503            par_civ2.ImageB=par_civ1.ImageB;
504        else
505            [par_civ2.ImageB,VideoObject_B] = read_image(ImageName_B_Civ2,FileType_B,VideoObject_B,FrameIndex_B_Civ2(ifield));
506        end
507        [FileInfo_A,VideoObject_A]=get_file_info(ImageName_A_Civ2);
508        par_civ2.ImageWidth=FileInfo_A.Width;
509        par_civ2.ImageHeight=FileInfo_A.Height;
510        if isfield(par_civ2,'Grid')% grid points set as input file
511            if ischar(par_civ2.Grid)%read the grid file if the input is a file name
512                par_civ2.Grid=dlmread(par_civ2.Grid);
513                par_civ2.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
[1089]514            end
[1148]515        else% automatic grid
516            minix=floor(par_civ2.Dx/2)-0.5;
517            maxix=minix+par_civ2.Dx*floor((par_civ2.ImageWidth-1)/par_civ2.Dx);
518            miniy=floor(par_civ2.Dy/2)-0.5;
519            maxiy=minix+par_civ2.Dy*floor((par_civ2.ImageHeight-1)/par_civ2.Dy);
520            [GridX,GridY]=meshgrid(minix:par_civ2.Dx:maxix,miniy:par_civ2.Dy:maxiy);
521            par_civ2.Grid(:,1)=reshape(GridX,[],1);
522            par_civ2.Grid(:,2)=reshape(GridY,[],1);
[1089]523        end
[1148]524        % end
[1164]525       
[1089]526        % get the guess from patch1 or patch2 (case 'CheckCiv3')
[1164]527       
[1148]528        if isfield (par_civ2,'CheckCiv3') && par_civ2.CheckCiv3 %get the guess from  patch2
529            SubRange= Data.Civ2_SubRange;
530            NbCentres=Data.Civ2_NbCentres;
531            Coord_tps=Data.Civ2_Coord_tps;
532            U_tps=Data.Civ2_U_tps;
533            V_tps=Data.Civ2_V_tps;
534            CivStage=Data.CivStage;%store the current CivStage
535            Civ1_Dt=Data.Civ2_Dt;
536            Data=[];%reinitialise the result structure Data
537            Data.ListGlobalAttribute={'Conventions','Program','CivStage'};
538            Data.Conventions='uvmat/civdata';% states the conventions used for the description of field variables and attributes
539            Data.Program='civ_series';
540            Data.CivStage=CivStage+1;%update the current civStage after reinitialisation of Data
[1089]541            Data.ListVarName={};
542            Data.VarDimName={};
[1148]543        else % get the guess from patch1
544            SubRange= Data.Civ1_SubRange;
545            NbCentres=Data.Civ1_NbCentres;
546            Coord_tps=Data.Civ1_Coord_tps;
547            U_tps=Data.Civ1_U_tps;
548            V_tps=Data.Civ1_V_tps;
549            Civ1_Dt=Data.Civ1_Dt;
550            Data.CivStage=4;
[1089]551        end
[1164]552       
[1089]553        Shiftx=zeros(size(par_civ2.Grid,1),1);% shift expected from civ1 data
554        Shifty=zeros(size(par_civ2.Grid,1),1);
555        nbval=zeros(size(par_civ2.Grid,1),1);% nbre of interpolated values at each grid point (from the different patch subdomains)
[1164]556       
[1089]557        NbSubDomain=size(SubRange,3);
558        for isub=1:NbSubDomain% for each sub-domain of Patch1
559            nbvec_sub=NbCentres(isub);% nbre of Civ vectors in the subdomain
560            ind_sel=find(par_civ2.Grid(:,1)>=SubRange(1,1,isub) & par_civ2.Grid(:,1)<=SubRange(1,2,isub) &...
561                par_civ2.Grid(:,2)>=SubRange(2,1,isub) & par_civ2.Grid(:,2)<=SubRange(2,2,isub));% grid points in the subdomain
562            if ~isempty(ind_sel)
563                epoints = par_civ2.Grid(ind_sel,:);% coordinates of interpolation sites (measurement grids)
564                ctrs=Coord_tps(1:nbvec_sub,:,isub) ;%(=initial points) ctrs
565                nbval(ind_sel)=nbval(ind_sel)+1;% records the number of values for each interpolation point (in case of subdomain overlap)
566                EM = tps_eval(epoints,ctrs);% thin plate spline (tps) coefficient
567                Shiftx(ind_sel)=Shiftx(ind_sel)+EM*U_tps(1:nbvec_sub+3,isub);%velocity shift estimated by tps from civ1
568                Shifty(ind_sel)=Shifty(ind_sel)+EM*V_tps(1:nbvec_sub+3,isub);
569            end
570        end
[1148]571        if par_civ2.CheckMask&&~isempty(par_civ2.Mask)
[1089]572            if isfield(par_civ2,'NbSlice')
573                [RootPath_mask,SubDir_mask,RootFile_mask,i1_mask,i2_mask,j1_mask,j2_mask,Ext_mask]=fileparts_uvmat(Param.ActionInput.Civ2.Mask);
574                i1_mask=mod(i1-1,par_civ2.NbSlice)+1;
575                maskname=fullfile_uvmat(RootPath_mask,SubDir_mask,RootFile_mask,Ext_mask,'_1',i1_mask);
576            else
577                maskname=Param.ActionInput.Civ2.Mask;
578            end
579            if strcmp(maskoldname,maskname)% mask exist, not already read in civ1
580                par_civ2.Mask=mask; %use mask already opened
581            else
582                if exist(maskname,'file')
[1148]583                    try
584                        par_civ2.Mask=imread(maskname);%update the mask, an store it for future use
585                    catch ME
586                        if ~isempty(ME.message)
587                            errormsg=['error reading input image: ' ME.message];
588                            disp_uvmat('ERROR',errormsg,checkrun)
589                            return
590                        end
[1089]591                    end
592                else
593                    par_civ2.Mask=[];
594                end
595                mask=par_civ2.Mask;
596                maskoldname=maskname;
597            end
598        end
[1164]599       
600       
[1148]601        if strcmp(Param.ActionInput.ListCompareMode,'displacement')
602            Civ1_Dt=1;
603            Civ2_Dt=1;
604        else
605            Civ2_Dt=Time(i2_civ2+1,j2_civ2+1)-Time(i1_civ2+1,j1_civ2+1);
[1089]606        end
[1164]607       
[1089]608        par_civ2.SearchBoxShift=(Civ2_Dt/Civ1_Dt)*[Shiftx(nbval>=1)./nbval(nbval>=1) Shifty(nbval>=1)./nbval(nbval>=1)];
609        % shift the grid points by half the expected shift to provide the correlation box position in image A
610        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];
611        if par_civ2.CheckDeformation
612            par_civ2.DUDX=DUDX(nbval>=1)./nbval(nbval>=1);
613            par_civ2.DUDY=DUDY(nbval>=1)./nbval(nbval>=1);
614            par_civ2.DVDX=DVDX(nbval>=1)./nbval(nbval>=1);
615            par_civ2.DVDY=DVDY(nbval>=1)./nbval(nbval>=1);
616        end
[1164]617       
[1089]618        % calculate velocity data (y and v in image indices, reverse to y component)
[1164]619       
[1089]620        [xtable, ytable, utable, vtable, ctable, F,result_conv,errormsg] = civ (par_civ2);
[1164]621       
[1089]622        list_param=(fieldnames(Param.ActionInput.Civ2))';
623        list_param(strcmp('TestCiv2',list_param))=[];% remove the parameter TestCiv2 from the list
624        Civ2_param=regexprep(list_param,'^.+','Civ2_$0');% insert 'Civ2_' before  each string in list_param
625        Civ2_param=[{'Civ2_ImageA','Civ2_ImageB','Civ2_Time','Civ2_Dt'} Civ2_param]; %insert the names of the two input images
626        %indicate the values of all the global attributes in the output data
627        if exist('ImageName_A','var')
628            Data.Civ2_ImageA=ImageName_A;
629            Data.Civ2_ImageB=ImageName_B;
630            if strcmp(Param.ActionInput.ListCompareMode,'displacement')
631                Data.Civ2_Time=Time(i2_civ2+1,j2_civ2+1);% the Time is the Time of the secodn image
632                Data.Civ2_Dt=1;% Time interval is 1, to yield displacement instead of velocity=displacement/Dt at reading
633            else
634                Data.Civ2_Time=(Time(i2_civ2+1,j2_civ2+1)+Time(i1_civ2+1,j1_civ2+1))/2;
635                Data.Civ2_Dt=Civ2_Dt;
636            end
637        end
638        for ilist=1:length(list_param)
639            Data.(Civ2_param{4+ilist})=Param.ActionInput.Civ2.(list_param{ilist});
640        end
641        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ2_param];
[1164]642       
[1089]643        nbvar=numel(Data.ListVarName);
644        % define the Civ2 variable (if Civ2 data are not replaced from previous calculation)
645        if isempty(find(strcmp('Civ2_X',Data.ListVarName),1))
[1148]646            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
[1089]647            Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2'}];
648            Data.VarAttribute{nbvar+1}.Role='coord_x';
649            Data.VarAttribute{nbvar+2}.Role='coord_y';
650            Data.VarAttribute{nbvar+3}.Role='vector_x';
651            Data.VarAttribute{nbvar+4}.Role='vector_y';
[1148]652            Data.VarAttribute{nbvar+5}.Role='ancillary';
653            Data.VarAttribute{nbvar+6}.Role='errorflag';
[1089]654        end
655        Data.Civ2_X=reshape(xtable,[],1);
656        Data.Civ2_Y=reshape(size(par_civ2.ImageA,1)-ytable+1,[],1);
657        Data.Civ2_U=reshape(utable,[],1);
658        Data.Civ2_V=reshape(-vtable,[],1);
659        Data.Civ2_C=reshape(ctable,[],1);
[1148]660        Data.Civ2_FF=reshape(F,[],1);
[1089]661        disp('civ2 performed')
[1148]662        time_civ2=toc(tstart_civ2);
[1089]663    elseif ~isfield(Data,'ListVarName') % we start there, using existing Civ2 data
664        if exist('ncfile','var')
665            CivFile=ncfile;
[1160]666            [Data,~,~,errormsg]=nc2struct(CivFile);%read civ1 and detect_false1 data in the existing netcdf file
[1089]667            if ~isempty(errormsg)
668                disp_uvmat('ERROR',errormsg,checkrun)
669                return
670            end
671        end
672    end
[1164]673   
[1089]674    %% Fix2
675    if isfield (Param.ActionInput,'Fix2')
[1148]676        disp('detect_false2 started')
[1089]677        list_param=fieldnames(Param.ActionInput.Fix2)';
678        Fix2_param=regexprep(list_param,'^.+','Fix2_$0');% insert 'Fix1_' before  each string in ListFixParam
679        %indicate the values of all the global attributes in the output data
680        for ilist=1:length(list_param)
681            Data.(Fix2_param{ilist})=Param.ActionInput.Fix2.(list_param{ilist});
682        end
683        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Fix2_param];
[1157]684        Data.Civ2_FF=detect_false(Param.ActionInput.Fix2,Data.Civ2_C,Data.Civ2_U,Data.Civ2_V,Data.Civ2_FF);
[1148]685        Data.CivStage=Data.CivStage+1;
[1089]686    end
[1164]687   
[1089]688    %% Patch2
689    if isfield (Param.ActionInput,'Patch2')
690        disp('patch2 started')
[1148]691        tstart_patch2=tic;
[1089]692        list_param=fieldnames(Param.ActionInput.Patch2)';
693        list_param(strcmp('TestPatch2',list_param))=[];% remove the parameter TestCiv1 from the list
694        Patch2_param=regexprep(list_param,'^.+','Patch2_$0');% insert 'Fix1_' before  each string in ListFixParam
695        %indicate the values of all the global attributes in the output data
696        for ilist=1:length(list_param)
697            Data.(Patch2_param{ilist})=Param.ActionInput.Patch2.(list_param{ilist});
698        end
699        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Patch2_param];
[1164]700       
[1089]701        nbvar=length(Data.ListVarName);
702        Data.ListVarName=[Data.ListVarName {'Civ2_U_smooth','Civ2_V_smooth','Civ2_SubRange','Civ2_NbCentres','Civ2_Coord_tps','Civ2_U_tps','Civ2_V_tps'}];
703        Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2',{'nb_coord','nb_bounds','nb_subdomain_2'},{'nb_subdomain_2'},...
704            {'nb_tps_2','nb_coord','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'}}];
[1165]705     
[1164]706       
[1165]707       
[1089]708        Data.VarAttribute{nbvar+1}.Role='vector_x';
709        Data.VarAttribute{nbvar+2}.Role='vector_y';
710        Data.VarAttribute{nbvar+5}.Role='coord_tps';
711        Data.VarAttribute{nbvar+6}.Role='vector_x';
712        Data.VarAttribute{nbvar+7}.Role='vector_y';
713        Data.Civ2_U_smooth=Data.Civ2_U;
714        Data.Civ2_V_smooth=Data.Civ2_V;
715        if isfield(Data,'Civ2_FF')
716            ind_good=find(Data.Civ2_FF==0);
717        else
718            ind_good=1:numel(Data.Civ2_X);
719        end
[1148]720        if isempty(ind_good)
721            disp_uvmat('ERROR','all vectors of civ2 are bad, check input parameters' ,checkrun)
722            return
723        end
[1164]724       
[1089]725        [Data.Civ2_SubRange,Data.Civ2_NbCentres,Data.Civ2_Coord_tps,Data.Civ2_U_tps,Data.Civ2_V_tps,tild,Ures,Vres,tild,FFres]=...
726            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);
727        Data.Civ2_U_smooth(ind_good)=Ures;
728        Data.Civ2_V_smooth(ind_good)=Vres;
729        Data.Civ2_FF(ind_good)=FFres;
730        Data.CivStage=Data.CivStage+1;
[1148]731        time_patch2=toc(tstart_patch2);
[1089]732        disp('patch2 performed')
733    end
[1164]734   
[1089]735    %% write result in a netcdf file if requested
[1148]736    % if CheckOutputFile
737    errormsg=struct2nc(ncfile_out,Data);
738    if isempty(errormsg)
739        disp([ncfile_out ' written'])
740        %[success,msg] = fileattrib(ncfile_out ,'+w','g');% done in struct2nc
741    else
742        disp(errormsg)
[1089]743    end
[1148]744    time_total=toc(tstart);
745    disp(['ellapsed time ' num2str(time_total/60,2) ' minutes'])
746    disp(['time civ1 ' num2str(time_civ1,2) ' s'])
747    disp(['time patch1 ' num2str(time_patch1,2) ' s'])
748    disp(['time civ2 ' num2str(time_civ2,2) ' s'])
749    disp(['time patch2 ' num2str(time_patch2,2) ' s'])
[1164]750   
[1089]751end
752
753
754% 'civ': function piv.m adapted from PIVlab http://pivlab.blogspot.com/
755%--------------------------------------------------------------------------
756% function [xtable ytable utable vtable typevector] = civ (image1,image2,ibx,iby step, subpixfinder, mask, roi)
757%
758% OUTPUT:
759% xtable: set of x coordinates
760% ytable: set of y coordiantes
761% utable: set of u displacements (along x)
762% vtable: set of v displacements (along y)
763% ctable: max image correlation for each vector
764% typevector: set of flags, =1 for good, =0 for NaN vectors
765%
766%INPUT:
767% par_civ: structure of input parameters, with fields:
768%  .ImageA: first image for correlation (matrix)
769%  .ImageB: second image for correlation(matrix)
770%  .CorrBoxSize: 1,2 vector giving the size of the correlation box in x and y
[1164]771%  .SearchRange:  1,2 vector giving the range of the search in x and y
[1089]772%  .SearchBoxShift: 1,2 vector or 2 column matrix (for civ2) giving the shift of the search box in x and y
773%  .CorrSmooth: =1 or 2 determines the choice of the sub-pixel determination of the correlation max
774%  .ImageWidth: nb of pixels of the image in x
775%  .Dx, Dy: mesh for the PIV calculation
776%  .Grid: grid giving the PIV calculation points (alternative to .Dx .Dy): centres of the correlation boxes in Image A
777%  .Mask: name of a mask file or mask image matrix itself
778%  .MinIma: thresholds for image luminosity
779%  .MaxIma
780%  .CheckDeformation=1 for subpixel interpolation and image deformation (linear transform)
781%  .DUDX: matrix of deformation obtained from patch at each grid point
782%  .DUDY
783%  .DVDX:
784%  .DVDY
785
[1148]786function [xtable,ytable,utable,vtable,wtable,ctable,FF,result_conv,errormsg] = civ3D (par_civ)
[1160]787%% check image sizes
[1164]788[npz,npy_ima,npx_ima]=size(par_civ.ImageA);% npz =
[1160]789if ~isequal(size(par_civ.ImageB),[npz npy_ima npx_ima])
790    errormsg='image pair with unequal size';
791    return
792end
[1089]793
794%% prepare measurement grid
[1160]795nbinterv_x=floor((npx_ima-1)/par_civ.Dx);
[1158]796gridlength_x=nbinterv_x*par_civ.Dx;
[1160]797minix=ceil((npx_ima-gridlength_x)/2);
798nbinterv_y=floor((npy_ima-1)/par_civ.Dy);
[1158]799gridlength_y=nbinterv_y*par_civ.Dy;
[1160]800miniy=ceil((npy_ima-gridlength_y)/2);
801[GridX,GridY]=meshgrid(minix:par_civ.Dx:npx_ima-1,miniy:par_civ.Dy:npy_ima-1);
[1148]802par_civ.Grid(:,:,1)=GridX;
803par_civ.Grid(:,:,2)=GridY;% increases with array index,
804[nbvec_y,nbvec_x,~]=size(par_civ.Grid);
805
[1160]806
[1089]807%% prepare correlation and search boxes
808ibx2=floor(par_civ.CorrBoxSize(1)/2);
809iby2=floor(par_civ.CorrBoxSize(2)/2);
[1164]810isx2=par_civ.SearchRange(1)+ibx2;
811isy2=par_civ.SearchRange(2)+iby2;
[1163]812isz2=par_civ.SearchRange(3);
[1148]813kref=isz2+1;%middle index of the z slice
[1089]814shiftx=round(par_civ.SearchBoxShift(:,1));%use the input shift estimate, rounded to the next integer value
815shifty=-round(par_civ.SearchBoxShift(:,2));% sign minus because image j index increases when y decreases
816if numel(shiftx)==1% case of a unique shift for the whole field( civ1)
[1160]817    shiftx=shiftx*ones(nbvec_y,nbvec_x);
818    shifty=shifty*ones(nbvec_y,nbvec_x);
[1089]819end
820
821%% Array initialisation and default output  if par_civ.CorrSmooth=0 (just the grid calculated, no civ computation)
[1148]822xtable=round(par_civ.Grid(:,:,1)+0.5)-0.5;
[1160]823%ytable=round(npy_ima-par_civ.Grid(:,:,2)+0.5)-0.5;% y index corresponding to the position in image coordiantes
824ytable=round(par_civ.Grid(:,:,2)+0.5)-0.5;
825utable=shiftx;
826vtable=shifty;
[1148]827wtable=zeros(size(utable));
[1160]828ctable=zeros(nbvec_y,nbvec_x);
829FF=false(nbvec_y,nbvec_x);
[1089]830result_conv=[];
831errormsg='';
832
833%% prepare mask
834check_MinIma=isfield(par_civ,'MinIma');% test for image luminosity threshold
835check_MaxIma=isfield(par_civ,'MaxIma') && ~isempty(par_civ.MaxIma);
836
837%% Apply mask
[1148]838% Convention for mask, IDEAS NOT IMPLEMENTED
[1089]839% mask >200 : velocity calculated
840%  200 >=mask>150;velocity not calculated, interpolation allowed (bad spots)
841% 150>=mask >100: velocity not calculated, nor interpolated
842%  100>=mask> 20: velocity not calculated, impermeable (no flux through mask boundaries)
843%  20>=mask: velocity=0
844checkmask=0;
[1148]845MinA=min(min(min(par_civ.ImageA)));
[1089]846if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
847    checkmask=1;
848    if ~isequal(size(par_civ.Mask),[npy_ima npx_ima])
849        errormsg='mask must be an image with the same size as the images';
850        return
851    end
[1160]852    check_undefined=(par_civ.Mask<200 & par_civ.Mask>=20 );% logical of the size of the image block =true for masked pixels
[1089]853end
854
855%% compute image correlations: MAINLOOP on velocity vectors
856corrmax=0;
857sum_square=1;% default
858mesh=1;% default
[1160]859% CheckDeformation=isfield(par_civ,'CheckDeformation')&& par_civ.CheckDeformation==1;
860% if CheckDeformation
861%     mesh=0.25;%mesh in pixels for subpixel image interpolation (x 4 in each direction)
862%     par_civ.CorrSmooth=2;% use SUBPIX2DGAUSS (take into account more points near the max)
863% end
[1089]864
865if par_civ.CorrSmooth~=0 % par_civ.CorrSmooth=0 implies no civ computation (just input image and grid points given)
[1148]866    for ivec_x=1:nbvec_x
867        for ivec_y=1:nbvec_y
[1157]868            iref=round(par_civ.Grid(ivec_y,ivec_x,1)+0.5);% xindex on the image A for the middle of the correlation box
[1160]869            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
[1148]870            subrange1_x=iref-ibx2:iref+ibx2;% x indices defining the first subimage
871            subrange1_y=jref-iby2:jref+iby2;% y indices defining the first subimage
872            subrange2_x=iref+shiftx(ivec_y,ivec_x)-isx2:iref+shiftx(ivec_y,ivec_x)+isx2;%x indices defining the second subimage
873            subrange2_y=jref+shifty(ivec_y,ivec_x)-isy2:jref+shifty(ivec_y,ivec_x)+isy2;%y indices defining the second subimage
874            image1_crop=MinA*ones(npz,numel(subrange1_y),numel(subrange1_x));% default value=min of image A
875            image2_crop=MinA*ones(npz,numel(subrange2_y),numel(subrange2_x));% default value=min of image A
[1160]876            check1_x=subrange1_x>=1 & subrange1_x<=npx_ima;% check which points in the subimage 1 are contained in the initial image 1
877            check1_y=subrange1_y>=1 & subrange1_y<=npy_ima;
878            check2_x=subrange2_x>=1 & subrange2_x<=npx_ima;% check which points in the subimage 2 are contained in the initial image 2
879            check2_y=subrange2_y>=1 & subrange2_y<=npy_ima;
[1148]880            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
881            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
[1160]882            if checkmask% case of mask images
883                mask1_crop=true(npz,2*iby2+1,2*ibx2+1);% default value=1 for mask
884                mask2_crop=true(npz,2*isy2+1,2*isx2+1);% default value=1 for mask
885                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
886                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
887                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
[1148]888                if sizemask > 1/2% eliminate point if more than half of the correlation box is masked
889                    FF(ivec_y,ivec_x)=1; %
890                    utable(ivec_y,ivec_x)=NaN;
891                    vtable(ivec_y,ivec_x)=NaN;
892                else
893                    image1_crop=image1_crop.*~mask1_crop;% put to zero the masked pixels (mask1_crop='true'=1)
894                    image2_crop=image2_crop.*~mask2_crop;
[1160]895                    image1_mean=mean(mean(image1_crop,2),3)/(1-sizemask);
896                    image2_mean=mean(mean(image2_crop,2),3)/(1-sizemask);
[1148]897                end
[1089]898            else
[1160]899                image1_mean=mean(mean(image1_crop,2),3);
900                image2_mean=mean(mean(image2_crop,2),3);
[1089]901            end
[1164]902           
[1148]903            if FF(ivec_y,ivec_x)==0
904                if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
[1160]905                    FF(ivec_y,ivec_x)=1;       %threshold on image minimum
[1164]906                   
[1148]907                elseif check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
[1160]908                    FF(ivec_y,ivec_x)=1;    %threshold on image maximum
[1148]909                end
910                if FF(ivec_y,ivec_x)==1
[1164]911                    utable(ivec_y,ivec_x)=NaN;
[1148]912                    vtable(ivec_y,ivec_x)=NaN;
[1089]913                else
[1160]914                    % case of mask
915                    % if checkmask
916                    %     image1_crop=(image1_crop-image1_mean).*~mask1_crop;%substract the mean, put to zero the masked parts
917                    %     image2_crop=(image2_crop-image2_mean).*~mask2_crop;% TO MODIFY !!!!!!!!!!!!!!!!!!!!!
918                    % else
919                    %     % image1_crop=(image1_crop-image1_mean);
920                    %     % image2_crop=(image2_crop-image2_mean);
921                    % end
[1164]922                   
[1163]923                    npxycorr=2*par_civ.SearchRange(1:2)+1;
924                    result_conv=zeros([2*par_civ.SearchRange(3)+1 npxycorr]);%initialise the conv product
925                    max_xy=zeros(2*par_civ.SearchRange(3)+1,1);%initialise the max correlation vs z
[1164]926                    xk=ones(npz,1);%initialise the x displacement corresponding to the max corr
927                    yk=ones(npz,1);%initialise the y displacement corresponding to the max corr
[1160]928                    subima1=squeeze(image1_crop(kref,:,:))-image1_mean(kref);
929                    for kz=1:npz
[1164]930                        subima2=squeeze(image2_crop(kz,:,:))-image2_mean(kz);
[1148]931                        correl_xy=conv2(subima2,flip(flip(subima1,2),1),'valid');
[1160]932                        result_conv(kz,:,:)=correl_xy;
[1164]933                        max_xy(kz)=max(max(correl_xy));
934                        [yk(kz),xk(kz)]=find(correl_xy==max_xy(kz),1);%find the indices of the maximum, use 0.999 to avoid rounding errors
[1148]935                    end
[1158]936                    [corrmax,dz]=max(max_xy);
[1160]937                    result_conv=result_conv*255/corrmax;% normalise with a max =255
[1158]938                    dx=xk(dz);
939                    dy=yk(dz);
[1160]940                    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
941                    sum_square=sum(sum(subima1.*subima1));
[1148]942                    sum_square=sum_square*sum(sum(subimage2_crop.*subimage2_crop));% product of variances of image 1 and 2
943                    sum_square=sqrt(sum_square);% srt of the variance product to normalise correlation
[1160]944                    % if ivec_x==3 && ivec_y==4
945                    %     'test'
946                    % end
[1158]947                    if ~isempty(dz)&& ~isempty(dy) && ~isempty(dx)
948                        if par_civ.CorrSmooth==1
949                            [vector,FF(ivec_y,ivec_x)] = SUBPIXGAUSS (result_conv,dx,dy,dz);
950                        elseif par_civ.CorrSmooth==2
951                            [vector,FF(ivec_y,ivec_x)] = SUBPIX2DGAUSS (result_conv,dx,dy,dz);
952                        else
953                            [vector,FF(ivec_y,ivec_x)] = quadr_fit(result_conv,dx,dy,dz);
954                        end
955                        utable(ivec_y,ivec_x)=vector(1)+shiftx(ivec_y,ivec_x);
[1164]956                        vtable(ivec_y,ivec_x)=-vector(2)+shifty(ivec_y,ivec_x);
[1158]957                        wtable(ivec_y,ivec_x)=vector(3);
958                        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)
959                        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)
960                        iref=round(xtable(ivec_y,ivec_x)+0.5);% nearest image index for the middle of the vector
961                        jref=round(ytable(ivec_y,ivec_x)+0.5);
[1164]962                        % if utable(ivec_y,ivec_x)==0 && vtable(ivec_y,ivec_x)==0
963                        %     'test'
964                        % end
[1158]965                        % eliminate vectors located in the mask
966                        if  checkmask && (iref<1 || jref<1 ||iref>npx_ima || jref>npy_ima ||( par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100))
967                            utable(ivec_y,ivec_x)=0;
968                            vtable(ivec_y,ivec_x)=0;
969                            FF(ivec_y,ivec_x)=1;
970                        end
971                        ctable(ivec_y,ivec_x)=corrmax/sum_square;% correlation value
[1148]972                    else
[1157]973                        FF(ivec_y,ivec_x)=true;
[1148]974                    end
[1089]975                end
976            end
977        end
978    end
979end
[1164]980ytable=npy_ima-ytable+1;%reverse from j index to image coordinate y
[1089]981result_conv=result_conv*corrmax/(255*sum_square);% keep the last correlation matrix for output
982
983%------------------------------------------------------------------------
984% --- Find the maximum of the correlation function after interpolation
985% OUPUT:
986% vector = optimum displacement vector with subpixel correction
[1157]987% FF =flag: ='true' max too close to the edge of the search box (1 pixel margin)
[1089]988% INPUT:
989% x,y: position of the maximum correlation at integer values
990
[1158]991function [vector,FF] = SUBPIXGAUSS (result_conv,x,y,z)
[1089]992%------------------------------------------------------------------------
[1158]993
994[npz,npy,npx]=size(result_conv);
[1160]995result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1  (to avoid divergence in the log)
[1089]996%the following 8 lines are copyright (c) 1998, Uri Shavit, Roi Gurka, Alex Liberzon, Technion ??? Israel Institute of Technology
997%http://urapiv.wordpress.com
[1157]998FF=false;
[1158]999peakz=z;peaky=y;peakx=x;
[1161]1000if z < npz && z > 1 && y < npy && y > 1 && x < npx && x > 1
1001    f0 = log(result_conv(z,y,x));
1002    f1 = log(result_conv(z-1,y,x));
1003    f2 = log(result_conv(z+1,y,x));
1004    peakz = peakz+ (f1-f2)/(2*f1-4*f0+2*f2);
[1164]1005   
[1161]1006    f1 = log(result_conv(z,y-1,x));
1007    f2 = log(result_conv(z,y+1,x));
1008    peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
[1164]1009   
[1161]1010    f1 = log(result_conv(z,y,x-1));
1011    f2 = log(result_conv(z,y,x+1));
1012    peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
1013else
1014    FF=true;
1015end
1016
[1158]1017vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1 peakz-floor(npz/2)-1];
1018
[1089]1019%------------------------------------------------------------------------
1020% --- Find the maximum of the correlation function after interpolation
1021function [vector,F] = SUBPIX2DGAUSS (result_conv,x,y)
1022%------------------------------------------------------------------------
1023% vector=[0 0]; %default
[1148]1024F=1;
[1089]1025peaky=y;
1026peakx=x;
1027result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1 (to avoid divergence in the log)
1028[npy,npx]=size(result_conv);
1029if (x < npx) && (y < npy) && (x > 1) && (y > 1)
1030    F=0;
1031    for i=-1:1
1032        for j=-1:1
1033            %following 15 lines based on
1034            %H. Nobach ??? M. Honkanen (2005)
1035            %Two-dimensional Gaussian regression for sub-pixel displacement
1036            %estimation in particle image velocimetry or particle position
1037            %estimation in particle tracking velocimetry
1038            %Experiments in Fluids (2005) 38: 511???515
1039            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
1040            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
1041            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
1042            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
1043            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
1044        end
1045    end
1046    c10=(1/6)*sum(sum(c10));
1047    c01=(1/6)*sum(sum(c01));
1048    c11=(1/4)*sum(sum(c11));
1049    c20=(1/6)*sum(sum(c20));
1050    c02=(1/6)*sum(sum(c02));
1051    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11^2);
1052    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11^2);
1053    if abs(deltax)<1
1054        peakx=x+deltax;
1055    end
1056    if abs(deltay)<1
1057        peaky=y+deltay;
1058    end
1059end
1060vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
1061
1062%------------------------------------------------------------------------
1063% --- Find the maximum of the correlation function after quadratic interpolation
1064function [vector,F] = quadr_fit(result_conv,x,y)
1065[npy,npx]=size(result_conv);
1066if x<4 || y<4 || npx-x<4 ||npy-y <4
[1148]1067    F=1;
[1089]1068    vector=[x y];
1069else
1070    F=0;
1071    x_ind=x-4:x+4;
1072    y_ind=y-4:y+4;
1073    x_vec=0.25*(x_ind-x);
1074    y_vec=0.25*(y_ind-y);
1075    [X,Y]=meshgrid(x_vec,y_vec);
1076    coord=[reshape(X,[],1) reshape(Y,[],1)];
1077    result_conv=reshape(result_conv(y_ind,x_ind),[],1);
1078   
1079   
1080    % n=numel(X);
1081    % x=[X Y];
1082    % X=X-0.5;
1083    % Y=Y+0.5;
1084    % y = (X.*X+2*Y.*Y+X.*Y+6) + 0.1*rand(n,1);
1085    p = polyfitn(coord,result_conv,2);
1086    A(1,1)=2*p.Coefficients(1);
1087    A(1,2)=p.Coefficients(2);
1088    A(2,1)=p.Coefficients(2);
1089    A(2,2)=2*p.Coefficients(4);
1090    vector=[x y]'-A\[p.Coefficients(3) p.Coefficients(5)]';
1091    vector=vector'-[floor(npx/2) floor(npy/2)]-1 ;
1092    % zg = polyvaln(p,coord);
1093    % figure
1094    % surf(x_vec,y_vec,reshape(zg,9,9))
1095    % hold on
1096    % plot3(X,Y,reshape(result_conv,9,9),'o')
1097    % hold off
1098end
1099
1100
[1148]1101function FF=detect_false(Param,C,U,V,FFIn)
1102FF=FFIn;%default, good vectors
1103% FF=1, for correlation max at edge, not set in this function
1104% FF=2, for too small correlation
1105% FF=3, for velocity outside bounds
1106% FF=4 for exclusion by difference with the smoothed field, not set in this function
[1089]1107
1108if isfield (Param,'MinCorr')
[1164]1109    FF(C<Param.MinCorr & FFIn==0)=2;
[1089]1110end
1111if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
1112    Umod= U.*U+V.*V;
1113    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
[1148]1114        U2Min=Param.MinVel*Param.MinVel;
1115        FF(Umod<U2Min & FFIn==0)=3;
[1089]1116    end
1117    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
[1164]1118        U2Max=Param.MaxVel*Param.MaxVel;
[1148]1119        FF(Umod>U2Max & FFIn==0)=3;
[1089]1120    end
1121end
1122
1123%------------------------------------------------------------------------
1124% --- determine the list of index pairs of processing file
1125function [i1_series,i2_series,j1_series,j2_series,check_bounds,NomTypeNc]=...
1126    find_pair_indices(str_civ,i_series,j_series,MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j)
1127%------------------------------------------------------------------------
1128i1_series=i_series;% set of first image indexes
1129i2_series=i_series;
1130j1_series=j_series;%ones(size(i_series));% set of first image numbers
1131j2_series=j_series;%ones(size(i_series));
1132r=regexp(str_civ,'^\D(?<ind>[i|j])=( -| )(?<num1>\d+)\|(?<num2>\d+)','names');
1133if ~isempty(r)
1134    mode=['D' r.ind];
1135    ind1=str2num(r.num1);
1136    ind2=str2num(r.num2);
1137else
1138    mode='j1-j2';
1139    r=regexp(str_civ,'^j= (?<num1>[a-z])-(?<num2>[a-z])','names');
1140    if ~isempty(r)
1141        NomTypeNc='_1ab';
1142    else
1143        r=regexp(str_civ,'^j= (?<num1>[A-Z])-(?<num2>[A-Z])','names');
1144        if ~isempty(r)
1145            NomTypeNc='_1AB';
1146        else
1147            r=regexp(str_civ,'^j= (?<num1>\d+)-(?<num2>\d+)','names');
1148            if ~isempty(r)
1149                NomTypeNc='_1_1-2';
1150            end
1151        end
1152    end
1153    if isempty(r)
1154        display('wrong pair mode input option')
1155    else
1156        ind1=stra2num(r.num1);
1157        ind2=stra2num(r.num2);
1158    end
1159end
1160switch mode
1161    case 'Di'
1162        i1_series=i_series-ind1;% set of first image numbers
1163        i2_series=i_series+ind2;
[1164]1164        check_bounds=i1_series(1)<MinIndex_i | i2_series(1)>MaxIndex_i;
[1089]1165        if isempty(j_series)
1166            NomTypeNc='_1-2';
1167        else
1168            j1_series=j_series;
1169            j2_series=j_series;
1170            NomTypeNc='_1-2_1';
1171        end
1172    case 'Dj'
1173        j1_series=j_series-ind1;
1174        j2_series=j_series+ind2;
1175        check_bounds=j1_series<MinIndex_j | j2_series>MaxIndex_j;
1176        NomTypeNc='_1_1-2';
1177    otherwise %bursts
1178        i1_series=i_series(1,:);% do not sweep the j index
1179        i2_series=i_series(1,:);
1180        j1_series=ind1*ones(1,size(i_series,2));% j index is fixed by pair choice
1181        j2_series=ind2*ones(1,size(i_series,2));
1182        check_bounds=zeros(size(i1_series));% no limitations due to min-max indices
1183end
1184
1185
1186
1187
Note: See TracBrowser for help on using the repository browser.