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

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

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

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