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

Last change on this file since 1158 was 1158, checked in by sommeria, 5 months ago

civ_3D corrected, automatic vector position modified in civ_series for better symmetry

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