source: trunk/src/series/civ_series.m @ 673

Last change on this file since 673 was 668, checked in by sommeria, 11 years ago

a few bugs corrected.
multimask introduced in merge_proj
displ_uvmat transformed into disp_uvmat

File size: 47.6 KB
RevLine 
[598]1%'civ_series': PIV function activated by the general GUI series
2% --- call the sub-functions:
3%   civ: PIV function itself
4%   fix: removes false vectors after detection by various criteria
5%   filter_tps: make interpolation-smoothing
[597]6%------------------------------------------------------------------------
[598]7% function [Data,errormsg,result_conv]= civ_series(Param,ncfile)
[597]8%
9%OUTPUT
[598]10% Data=structure containing the PIV results and information on the processing parameters
11% errormsg=error message char string, default=''
12% resul_conv: image inter-correlation function for the last grid point (used for tests)
[597]13%
14%INPUT:
[598]15% Param: input images and processing parameters
16%     .Civ1: for civ1
17%     .Fix1:
18%     .Patch1:
19%     .Civ2: for civ2
20%     .Fix2:
21%     .Patch2:
22% ncfile: name of a netcdf file to be created for the result (extension .nc)
[597]23%
[598]24%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
25%  Copyright  2011, LEGI / CNRS-UJF-INPG, joel.sommeria@legi.grenoble-inp.fr.
26%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
27%     This is part of the toolbox UVMAT.
28%
29%     UVMAT is free software; you can redistribute it and/or modify
30%     it under the terms of the GNU General Public License as published by
31%     the Free Software Foundation; either version 2 of the License, or
32%     (at your option) any later version.
33%
34%     UVMAT is distributed in the hope that it will be useful,
35%     but WITHOUT ANY WARRANTY; without even the implied warranty of
36%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
37%     GNU General Public License (open UVMAT/COPYING.txt) for more details.
38%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
[597]39
[598]40function [Data,errormsg,result_conv]= civ_series(Param,ncfile)
41errormsg='';
42path_series=fileparts(which('series'));
43addpath(fullfile(path_series,'series'))
[606]44%% set the input elements needed on the GUI series when the action is selected in the menu ActionName or InputTable refreshed
[597]45if isstruct(Param) && isequal(Param.Action.RUN,0)
[598]46    Data=civ_input(Param);% introduce the civ parameters using the GUI civ_input
[668]47    if isempty(Data)
48        Data=Param;% if  civ_input has been cancelled, keep previous parameters
49    end
[606]50    Data.Program=mfilename;%gives the name of the current function
51    Data.AllowInputSort='off';% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
52    Data.WholeIndexRange='off';% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
53    Data.NbSlice='off'; %nbre of slices ('off' by default)
54    Data.VelType='off';% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
55    Data.FieldName='off';% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
56    Data.FieldTransform = 'off';%can use a transform function
57    Data.ProjObject='off';%can use projection object(option 'off'/'on',
58    Data.Mask='off';%can use mask option   (option 'off'/'on', 'off' by default)
59    Data.OutputDirExt='.civ';%set the output dir extension
[645]60    Data.OutputFileMode='NbInput_i';% one output file expected per value of i index (used for waitbar)
[606]61    filecell=get_file_series(Param);%check existence of the first input file
62    if ~exist(filecell{1,1},'file')
63        msgbox_uvmat('WARNING','the first input file does not exist')
[609]64    else
65        FileType=get_file_type(filecell{1,1});
66        if isempty(find(strcmp(FileType,{'civdata','image','multimage','mmreader','video'})));% =1 for images
67            msgbox_uvmat('ERROR',['bad input file type for ' mfilename ': an image or civdata file is needed'])
68        end
[606]69    end
[598]70    return
[597]71end
72
73%% read input parameters from an xml file if input is a file name (batch mode)
74checkrun=1;
75if ischar(Param)
76    Param=xml2struct(Param);% read Param as input file (batch case)
77    checkrun=0;
78end
[668]79if ~isfield(Param,'ActionInput')
80     disp_uvmat('ERROR','no parameter set for PIV',checkrun)
81        return
82end
[624]83hseries=findobj(allchild(0),'Tag','series');
84RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
85WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
[597]86
[605]87%% input files and indexing
[598]88NbField=1;
[635]89MaxIndex_i=Param.IndexRange.MaxIndex_i;
90MinIndex_i=Param.IndexRange.MinIndex_i;
91MaxIndex_j=1;MinIndex_j=1;
92if isfield(Param.IndexRange,'MaxIndex_j')&& isfield(Param.IndexRange,'MinIndex_j')
93    MaxIndex_j=Param.IndexRange.MaxIndex_j;
94    MinIndex_j=Param.IndexRange.MinIndex_j;
95end
[598]96if isfield(Param,'InputTable')
97    [filecell,i_series,tild,j_series]=get_file_series(Param);
[610]98    if ~exist(filecell{1,1},'file')
[668]99        disp_uvmat('ERROR',' the first input file does not exist',checkrun)
[610]100        return
101    else
102        FileType=get_file_type(filecell{1,1});
[661]103        iview_nc=0;% series index (iview) for an input nc file (for civ2 or patch2)
104        iview_A=0;% series index (iview) for the first image series
105        iview_B=0;% series index (iview) for the second image series (only non zero for option 'shift' )
[610]106        switch FileType
107            case 'civdata';% =1 for images
108                iview_nc=1;
109                if size(filecell,1)>=2
110                    iview_A=2;iview_B=2;
111                    if size(filecell,1)>=3
112                        iview_B=3;
113                    end
114                end
115            case {'image','multimage','mmreader','video'}
116                iview_A=1;
117                if size(filecell,1)>=2
118                    iview_B=2;
119                end
120        end
[609]121    end
[610]122    if iview_A~=0
123        [FileType_A,FileInfo_A,VideoObject_A]=get_file_type(filecell{1,1});
124        if isempty(strcmp(FileType_A,{'multimage','mmreader','video'}))
125            displ(['ERROR: the file line ' num2str(iview_A) ' must be an image'])
126        end
[661]127        RootPath_A=Param.InputTable{1,1};
128        RootFile_A=Param.InputTable{1,3};
129        SubDir_A=Param.InputTable{1,2};
130        NomType_A=Param.InputTable{1,4};
131        FileExt_A=Param.InputTable{1,5};
[597]132    end
[610]133    if iview_B==0
134        FileType_B=FileType_A;
[635]135        VideoObject_B=VideoObject_A;
[661]136        RootPath_B=RootPath_A;
137        RootFile_B=RootFile_A;
138        SubDir_B=SubDir_A;
139        NomType_B=NomType_A;
140        FileExt_B=FileExt_A;
[610]141        PairCiv2='';
[661]142        switch Param.ActionInput.ListCompareMode
143            case 'PIV'
144                PairCiv1=Param.ActionInput.PairIndices.ListPairCiv1;
145                if isfield(Param.ActionInput.PairIndices,'ListPairCiv2')
146                    PairCiv2=Param.ActionInput.PairIndices.ListPairCiv2;
147                end
148                [i1_series_Civ1,i2_series_Civ1,j1_series_Civ1,j2_series_Civ1,check_bounds,NomTypeNc]=...
149                    find_pair_indices(PairCiv1,i_series{1},j_series{1},MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j);
150                if ~isempty(PairCiv2)
151                    [i1_series_Civ2,i2_series_Civ2,j1_series_Civ2,j2_series_Civ2,check_bounds_Civ2]=...
152                        find_pair_indices(PairCiv2,i_series{1},j_series{1},MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j);
153                    check_bounds=check_bounds | check_bounds_Civ2;
154                end
155                i1_series_Civ1=i1_series_Civ1(~check_bounds);
156                i2_series_Civ1=i2_series_Civ1(~check_bounds);
157                j1_series_Civ1=j1_series_Civ1(~check_bounds);
158                j2_series_Civ1=j2_series_Civ1(~check_bounds);
159            case 'displacement'
160                i1_series_Civ1=Param.ActionInput.OriginIndex*ones(size(i_series{1}));
161                i2_series_Civ1=i_series{1};i2_series_Civ2=i_series{1};
162                j1_series_Civ1=ones(size(i_series{1}));% first j index is 1
163                if isempty(j_series{1})
164                    j2_series_Civ1=ones(size(i_series{1}));
165                else
166                    j2_series_Civ1=j_series{1};
167                end
168                i1_series_Civ2=i1_series_Civ1;
169                j1_series_Civ2=j1_series_Civ1;
170                j2_series_Civ2=j2_series_Civ1;
171                NomTypeNc=NomType;
[610]172        end
173        if ~isempty(PairCiv2)
174            i1_series_Civ2=i1_series_Civ2(~check_bounds);
175            i2_series_Civ2=i2_series_Civ2(~check_bounds);
176            j1_series_Civ2=j1_series_Civ2(~check_bounds);
177            j2_series_Civ2=j2_series_Civ2(~check_bounds);
178            if isempty(j_series{1})
179                FrameIndex_A_Civ2=i1_series_Civ2;
180                FrameIndex_B_Civ2=i2_series_Civ2;
181            else
182                FrameIndex_A_Civ2=j1_series_Civ2;
183                FrameIndex_B_Civ2=j2_series_Civ2;
184            end
185        end
186    else
[635]187        [FileType_B,FileInfo,VideoObject_B]=get_file_type(filecell{2,1});
[661]188        if ~ismember(FileType_B,{'image','multimage','mmreader','video'})
[668]189            disp_uvmat('ERROR',['the file line ' num2str(iview_B) ' must be an image'],checkrun)
[635]190        end
[661]191        i1_series_Civ1=i_series{1};i1_series_Civ2=i_series{1};
192        i2_series_Civ1=i_series{1};i2_series_Civ2=i_series{1};
193        if isempty(j_series{1})
194            j1_series_Civ1=ones(size(i_series{1}));
195            j2_series_Civ1=ones(size(i_series{1}));
196        else
197            j1_series_Civ1=j_series{1};
198            j2_series_Civ1=j_series{1};
199        end
200        j1_series_Civ2=j1_series_Civ1;
201        j2_series_Civ2=j2_series_Civ1;
202        NomTypeNc=NomType_A;
203        RootPath_B=Param.InputTable{2,1};
204        RootFile_B=Param.InputTable{2,3};
205        SubDir_B=Param.InputTable{2,2};
206        NomType_B=Param.InputTable{2,4};
207        FileExt_B=Param.InputTable{2,5};
[597]208    end
[661]209    if isempty(j_series{1})
210        FrameIndex_A_Civ1=i1_series_Civ1;
211        FrameIndex_B_Civ1=i2_series_Civ1;
212    else
213        FrameIndex_A_Civ1=j1_series_Civ1;
214        FrameIndex_B_Civ1=j2_series_Civ1;
215    end
[597]216end
[610]217NbField=numel(i1_series_Civ1);
[597]218
[605]219%% Output directory
220OutputDir=[Param.OutputSubDir Param.OutputDirExt];
221
222Data.ListGlobalAttribute={'Conventions','Program','CivStage'};
223Data.Conventions='uvmat/civdata';% states the conventions used for the description of field variables and attributes
224Data.Program='civ_series';
225Data.CivStage=0;%default
226ListVarCiv1={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F'}; %variables to read
227ListVarFix1={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F','Civ1_FF'};
228mask='';
229maskname='';%default
230check_civx=0;%default
231check_civ1=0;%default
232check_patch1=0;%default
233
[606]234%% get timing from the ImaDoc file or input video
[661]235XmlFileName=find_imadoc(RootPath_A,SubDir_A,RootFile_A,FileExt_A);
[609]236time=[];
237if ~isempty(XmlFileName)
238    XmlData=imadoc2struct(XmlFileName);
239        if isfield(XmlData,'Time')
240            time=XmlData.Time;
241            TimeSource='xml';
242        end
243        if isfield(XmlData,'Camera')
244            if isfield(XmlData.Camera,'NbSlice')&& ~isempty(XmlData.Camera.NbSlice)
245                NbSlice_calib{iview}=XmlData.Camera.NbSlice;% Nbre of slices for Zindex in phys transform
246                if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
247                    msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
248                end
249            end
250            if isfield(XmlData.Camera,'TimeUnit')&& ~isempty(XmlData.Camera.TimeUnit)
251                TimeUnit=XmlData.Camera.TimeUnit;
252            end
253        end
254end
[637]255if isempty(time) && ~isempty(find(strcmp(FileType_A,{'mmreader','video'})))% case of video input
[610]256    time=zeros(2,FileInfo_A.NumberOfFrames+1);
257    time(2,:)=(0:1/FileInfo_A.FrameRate:(FileInfo_A.NumberOfFrames)/FileInfo_A.FrameRate);
258    TimeSource='video';
259    % set(han:dles.Dt_txt,'String',['Dt=' num2str(1000/imainfo.FrameRate) 'ms']);%display the elementary time interval in millisec
260    ColorType='truecolor';
[609]261end
[637]262if isempty(time)% time = index i +0.001 index j by default
263    time=(MinIndex_i:MaxIndex_i)'*ones(1,MaxIndex_j-MinIndex_j+1);
264    time=time+0.001*ones(MaxIndex_i-MinIndex_i+1,1)*(MinIndex_j:MaxIndex_j);
265    time=[zeros(1,MaxIndex_j-MinIndex_j+1);time];% insert a first line of zeros
266    time=[zeros(MaxIndex_i-MinIndex_i+2,1) time];% insert a first column of zeros
267end
268   
[610]269if length(FileInfo_A) >1 %case of image with multiple frames
270    nbfield=length(FileInfo_A);
271    nbfield_j=1;
272end
[609]273
[598]274%%%%% MAIN LOOP %%%%%%
275for ifield=1:NbField
[635]276    update_waitbar(WaitbarHandle,ifield/NbField)
277    if ~isempty(RUNHandle) && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
[624]278        disp('program stopped by user')
279        break
280    end
[598]281    %% Civ1
282    if isfield (Param.ActionInput,'Civ1')
283        par_civ1=Param.ActionInput.Civ1;
284        if isfield(par_civ1,'reverse_pair')% A REVOIR
285            if par_civ1.reverse_pair
286                if ischar(par_civ1.ImageB)
287                    temp=par_civ1.ImageA;
288                    par_civ1.ImageA=imread(par_civ1.ImageB);
289                end
290                if ischar(temp)
291                    par_civ1.ImageB=imread(temp);
292                end
[597]293            end
[598]294        else
[661]295            ImageName_A=fullfile_uvmat(RootPath_A,SubDir_A,RootFile_A,FileExt_A,NomType_A,i1_series_Civ1(ifield),[],j1_series_Civ1(ifield));
[610]296            [par_civ1.ImageA,VideoObject_A] = read_image(ImageName_A,FileType_A,VideoObject_A,FrameIndex_A_Civ1(ifield));
[661]297            ImageName_B=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i2_series_Civ1(ifield),[],j2_series_Civ1(ifield));
[610]298            [par_civ1.ImageB,VideoObject_B] = read_image(ImageName_B,FileType_B,VideoObject_B,FrameIndex_B_Civ1(ifield));
[597]299        end
[661]300        if strcmp(Param.ActionInput.ListCompareMode,'PIV')
301        ncfile=fullfile_uvmat(RootPath_A,OutputDir,RootFile_A,'.nc',NomTypeNc,i1_series_Civ1(ifield),i2_series_Civ1(ifield),...
[598]302            j1_series_Civ1(ifield),j2_series_Civ1(ifield));
[661]303        else
304                   ncfile=fullfile_uvmat(RootPath_A,OutputDir,RootFile_A,'.nc',NomTypeNc,i2_series_Civ1(ifield),[],...
305            j1_series_Civ1(ifield),j2_series_Civ1(ifield));
306        end
[610]307        par_civ1.ImageWidth=FileInfo_A.Width;
308        par_civ1.ImageHeight=FileInfo_A.Height;
[598]309        list_param=(fieldnames(Param.ActionInput.Civ1))';
[606]310        Civ1_param=regexprep(list_param,'^.+','Civ1_$0');% insert 'Civ1_' before  each string in list_param
311        Civ1_param=[{'Civ1_ImageA','Civ1_ImageB','Civ1_Time','Civ1_Dt'} Civ1_param]; %insert the names of the two input images
312        %indicate the values of all the global attributes in the output data
313        Data.Civ1_ImageA=ImageName_A;
314        Data.Civ1_ImageB=ImageName_B;
[610]315        i1=i1_series_Civ1(ifield);
316        i2=i1;
317        if ~isempty(i2_series_Civ1)
318            i2=i2_series_Civ1(ifield);
319        end
320        j1=1;
321        if ~isempty(j1_series_Civ1)
322            j1=j1_series_Civ1(ifield);
323        end
324        j2=j1;
325        if ~isempty(j2_series_Civ1)
326            j2=j2_series_Civ1(ifield);
327        end
[637]328        Data.Civ1_Time=(time(i2+1,j2+1)+time(i1+1,j1+1))/2;
329        Data.Civ1_Dt=time(i2+1,j2+1)-time(i1+1,j1+1);
[598]330        for ilist=1:length(list_param)
[606]331            Data.(Civ1_param{4+ilist})=Param.ActionInput.Civ1.(list_param{ilist});
[597]332        end
[604]333        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ1_param];
[598]334        Data.CivStage=1;
[597]335       
[598]336        % set the list of variables
337        Data.ListVarName={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_F','Civ1_C'};%  cell array containing the names of the fields to record
338        Data.VarDimName={'nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1'};
339        Data.VarAttribute{1}.Role='coord_x';
340        Data.VarAttribute{2}.Role='coord_y';
341        Data.VarAttribute{3}.Role='vector_x';
342        Data.VarAttribute{4}.Role='vector_y';
343        Data.VarAttribute{5}.Role='warnflag';
[597]344       
[598]345        if strcmp(Param.ActionInput.ListCompareMode, 'PIV volume')
346            Data.ListVarName=[Data.ListVarName 'Civ1_Z'];
347            Data.Civ1_X=[];Data.Civ1_Y=[];Data.Civ1_Z=[];
348            Data.Civ1_U=[];Data.Civ1_V=[];Data.Civ1_C=[];Data.Civ1_F=[];
349            for ivol=1:NbSlice
350                % caluclate velocity data (y and v in indices, reverse to y component)
351                [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ1);
352                if ~isempty(errormsg)
353                    return
354                end
355                Data.Civ1_X=[Data.Civ1_X reshape(xtable,[],1)];
356                Data.Civ1_Y=[Data.Civ1_Y reshape(Param.Civ1.ImageHeight-ytable+1,[],1)];
357                Data.Civ1_Z=[Data.Civ1_Z ivol*ones(numel(xtable),1)];% z=image index in image coordinates
358                Data.Civ1_U=[Data.Civ1_U reshape(utable,[],1)];
359                Data.Civ1_V=[Data.Civ1_V reshape(-vtable,[],1)];
360                Data.Civ1_C=[Data.Civ1_C reshape(ctable,[],1)];
361                Data.Civ1_F=[Data.Civ1_C reshape(F,[],1)];
362            end
363        else %usual PIV
364            % caluclate velocity data (y and v in indices, reverse to y component)
365            [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ1);
[597]366            if ~isempty(errormsg)
367                return
368            end
[598]369            Data.Civ1_X=reshape(xtable,[],1);
370            Data.Civ1_Y=reshape(par_civ1.ImageHeight-ytable+1,[],1);
371            Data.Civ1_U=reshape(utable,[],1);
372            Data.Civ1_V=reshape(-vtable,[],1);
373            Data.Civ1_C=reshape(ctable,[],1);
374            Data.Civ1_F=reshape(F,[],1);
[597]375        end
[598]376    else
377        if exist('ncfile','var')
378            CivFile=ncfile;
379        elseif isfield(Param.Patch1,'CivFile')
380            CivFile=Param.Patch1.CivFile;
381        end
382        Data=nc2struct(CivFile,'ListGlobalAttribute','absolut_time_T0'); %look for the constant 'absolut_time_T0' to detect old civx data format
383        if isfield(Data,'Txt')
384            errormsg=Data.Txt;
385            return
386        end
387        if ~isempty(Data.absolut_time_T0')%read civx file
388            check_civx=1;% test for old civx data format
389            [Data,vardetect,ichoice]=nc2struct(CivFile);%read the variables in the netcdf file
390        else
391            Data=nc2struct(CivFile);%read civ1 and fix1 data in the existing netcdf file
392        end
[597]393    end
394   
[598]395    %% Fix1
396    if isfield (Param.ActionInput,'Fix1')
397        ListFixParam=fieldnames(Param.ActionInput.Fix1);
398        for ilist=1:length(ListFixParam)
399            ParamName=ListFixParam{ilist};
400            ListName=['Fix1_' ParamName];
401            eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
402            eval(['Data.' ListName '=Param.ActionInput.Fix1.' ParamName ';'])
403        end
404        if check_civx
405            if ~isfield(Data,'fix')
406                Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix'];
407                Data.fix=1;
408                Data.ListVarName=[Data.ListVarName {'vec_FixFlag'}];
409                Data.VarDimName=[Data.VarDimName {'nb_vectors'}];
410            end
411            Data.vec_FixFlag=fix(Param.ActionInput.Fix1,Data.vec_F,Data.vec_C,Data.vec_U,Data.vec_V,Data.vec_X,Data.vec_Y);
412        else
413            Data.ListVarName=[Data.ListVarName {'Civ1_FF'}];
414            Data.VarDimName=[Data.VarDimName {'nb_vec_1'}];
415            nbvar=length(Data.ListVarName);
416            Data.VarAttribute{nbvar}.Role='errorflag';
417            Data.Civ1_FF=fix(Param.ActionInput.Fix1,Data.Civ1_F,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V);
418            Data.CivStage=2;
419        end
[597]420    end
[598]421    %% Patch1
422    if isfield (Param.ActionInput,'Patch1')
423        if check_civx
424            errormsg='Civ Matlab input needed for patch';
425            return
426        end
427       
428        Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch1_Rho','Patch1_Threshold','Patch1_SubDomain'}];
429        Data.Patch1_FieldSmooth=Param.ActionInput.Patch1.FieldSmooth;
430        Data.Patch1_MaxDiff=Param.ActionInput.Patch1.MaxDiff;
431        Data.Patch1_SubDomainSize=Param.ActionInput.Patch1.SubDomainSize;
432        nbvar=length(Data.ListVarName);
433        Data.ListVarName=[Data.ListVarName {'Civ1_U_smooth','Civ1_V_smooth','Civ1_SubRange','Civ1_NbCentres','Civ1_Coord_tps','Civ1_U_tps','Civ1_V_tps'}];
434        Data.VarDimName=[Data.VarDimName {'nb_vec_1','nb_vec_1',{'nb_coord','nb_bounds','nb_subdomain_1'},'nb_subdomain_1',...
435            {'nb_tps_1','nb_coord','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'}}];
436        Data.VarAttribute{nbvar+1}.Role='vector_x';
437        Data.VarAttribute{nbvar+2}.Role='vector_y';
438        Data.VarAttribute{nbvar+5}.Role='coord_tps';
439        Data.VarAttribute{nbvar+6}.Role='vector_x';
440        Data.VarAttribute{nbvar+7}.Role='vector_y';
441        Data.Civ1_U_smooth=zeros(size(Data.Civ1_X));
442        Data.Civ1_V_smooth=zeros(size(Data.Civ1_X));
443        if isfield(Data,'Civ1_FF')
444            ind_good=find(Data.Civ1_FF==0);
[597]445        else
[598]446            ind_good=1:numel(Data.Civ1_X);
[597]447        end
[598]448        [Data.Civ1_SubRange,Data.Civ1_NbCentres,Data.Civ1_Coord_tps,Data.Civ1_U_tps,Data.Civ1_V_tps,tild,Ures, Vres,tild,FFres]=...
449            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);
450        Data.Civ1_U_smooth(ind_good)=Ures;
451        Data.Civ1_V_smooth(ind_good)=Vres;
452        Data.Civ1_FF(ind_good)=FFres;
453        Data.CivStage=3;
[597]454    end
455   
[598]456    %% Civ2
457    if isfield (Param.ActionInput,'Civ2')
458        par_civ2=Param.ActionInput.Civ2;
459        par_civ2.ImageA=[];
460        par_civ2.ImageB=[];
461        %         if ~isfield(Param.Civ1,'ImageA')
[668]462        ImageName_A_Civ2=fullfile_uvmat(RootPath_A,SubDir_A,RootFile_A,FileExt_A,NomType_A,i1_series_Civ2(ifield),[],j1_series_Civ2(ifield));
[598]463
[635]464        if strcmp(ImageName_A_Civ2,ImageName_A) && isequal(FrameIndex_A_Civ1(ifield),FrameIndex_A_Civ2(ifield))
[598]465            par_civ2.ImageA=par_civ1.ImageA;
466        else
[635]467            [par_civ2.ImageA,VideoObject_A] = read_image(ImageName_A,FileType_A,VideoObject_A,FrameIndex_A_Civ2(ifield));
[597]468        end
[668]469        ImageName_B_Civ2=fullfile_uvmat(RootPath_B,SubDir_B,RootFile_B,FileExt_B,NomType_B,i2_series_Civ2(ifield),[],j2_series_Civ2(ifield));
[601]470        if strcmp(ImageName_B_Civ2,ImageName_B) && isequal(FrameIndex_B_Civ1(ifield),FrameIndex_B_Civ2)
[598]471            par_civ2.ImageB=par_civ1.ImageB;
[597]472        else
[635]473            [par_civ2.ImageB,VideoObject_B] = read_image(ImageName_B,FileType_B,VideoObject_B,FrameIndex_B_Civ2(ifield));
[598]474        end     
475       
[668]476        ncfile=fullfile_uvmat(RootPath_A,OutputDir,RootFile_A,'.nc',NomTypeNc,i1_series_Civ2(ifield),i2_series_Civ2(ifield),...
[598]477            j1_series_Civ2(ifield),j2_series_Civ2(ifield));
[635]478        par_civ2.ImageWidth=FileInfo_A.Width;
479        par_civ2.ImageHeight=FileInfo_A.Height;
[598]480       
481        if isfield(par_civ2,'Grid')% grid points set as input file
482            if ischar(par_civ2.Grid)%read the grid file if the input is a file name
483                par_civ2.Grid=dlmread(par_civ2.Grid);
484                par_civ2.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
485            end
486        else% automatic grid
487            minix=floor(par_civ2.Dx/2)-0.5;
488            maxix=minix+par_civ2.Dx*floor((par_civ2.ImageWidth-1)/par_civ2.Dx);
489            miniy=floor(par_civ2.Dy/2)-0.5;
490            maxiy=minix+par_civ2.Dy*floor((par_civ2.ImageHeight-1)/par_civ2.Dy);
491            [GridX,GridY]=meshgrid(minix:par_civ2.Dx:maxix,miniy:par_civ2.Dy:maxiy);
492            par_civ2.Grid(:,1)=reshape(GridX,[],1);
493            par_civ2.Grid(:,2)=reshape(GridY,[],1);
[597]494        end
[598]495        Shiftx=zeros(size(par_civ2.Grid,1),1);% shift expected from civ1 data
496        Shifty=zeros(size(par_civ2.Grid,1),1);
497        nbval=zeros(size(par_civ2.Grid,1),1);
498        if par_civ2.CheckDeformation
499            DUDX=zeros(size(par_civ2.Grid,1),1);
500            DUDY=zeros(size(par_civ2.Grid,1),1);
501            DVDX=zeros(size(par_civ2.Grid,1),1);
502            DVDY=zeros(size(par_civ2.Grid,1),1);
[597]503        end
[598]504        NbSubDomain=size(Data.Civ1_SubRange,3);
505        % get the guess from patch1
506        for isub=1:NbSubDomain
507            nbvec_sub=Data.Civ1_NbCentres(isub);
508            ind_sel=find(GridX>=Data.Civ1_SubRange(1,1,isub) & GridX<=Data.Civ1_SubRange(1,2,isub) & GridY>=Data.Civ1_SubRange(2,1,isub) & GridY<=Data.Civ1_SubRange(2,2,isub));
509            epoints = [GridX(ind_sel) GridY(ind_sel)];% coordinates of interpolation sites
510            ctrs=Data.Civ1_Coord_tps(1:nbvec_sub,:,isub) ;%(=initial points) ctrs
511            nbval(ind_sel)=nbval(ind_sel)+1;% records the number of values for eacn interpolation point (in case of subdomain overlap)
512            EM = tps_eval(epoints,ctrs);
513            Shiftx(ind_sel)=Shiftx(ind_sel)+EM*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
514            Shifty(ind_sel)=Shifty(ind_sel)+EM*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
515            if par_civ2.CheckDeformation
516                [EMDX,EMDY] = tps_eval_dxy(epoints,ctrs);%2D matrix of distances between extrapolation points epoints and spline centres (=site points) ctrs
517                DUDX(ind_sel)=DUDX(ind_sel)+EMDX*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
518                DUDY(ind_sel)=DUDY(ind_sel)+EMDY*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
519                DVDX(ind_sel)=DVDX(ind_sel)+EMDX*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
520                DVDY(ind_sel)=DVDY(ind_sel)+EMDY*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
[597]521            end
522        end
[598]523        mask='';
524        if par_civ2.CheckMask&&~isempty(par_civ2.Mask)&& ~strcmp(maskname,par_civ2.Mask)% mask exist, not already read in civ1
525            mask=imread(par_civ2.Mask);
526        end
527        ibx2=ceil(par_civ2.CorrBoxSize(1)/2);
528        iby2=ceil(par_civ2.CorrBoxSize(2)/2);
529        par_civ2.SearchBoxSize(1)=2*ibx2+9;% search ara +-4 pixels around the guess
530        par_civ2.SearchBoxSize(2)=2*iby2+9;
531        par_civ2.SearchBoxShift=[Shiftx(nbval>=1)./nbval(nbval>=1) Shifty(nbval>=1)./nbval(nbval>=1)];
532        par_civ2.Grid=[GridX(nbval>=1)-par_civ2.SearchBoxShift(:,1)/2 GridY(nbval>=1)-par_civ2.SearchBoxShift(:,2)/2];% grid taken at the extrapolated origin of the displacement vectors
533        if par_civ2.CheckDeformation
534            par_civ2.DUDX=DUDX./nbval;
535            par_civ2.DUDY=DUDY./nbval;
536            par_civ2.DVDX=DVDX./nbval;
537            par_civ2.DVDY=DVDY./nbval;
538        end
539        % caluclate velocity data (y and v in indices, reverse to y component)
540        [xtable ytable utable vtable ctable F] = civ (par_civ2);
541
542        list_param=(fieldnames(Param.ActionInput.Civ2))';
[606]543        Civ2_param=regexprep(list_param,'^.+','Civ2_$0');% insert 'Civ2_' before  each string in list_param
544        Civ2_param=[{'Civ2_ImageA','Civ2_ImageB','Civ2_Time','Civ2_Dt'} Civ2_param]; %insert the names of the two input images
545        %indicate the values of all the global attributes in the output data
546        Data.Civ2_ImageA=ImageName_A;
547        Data.Civ2_ImageB=ImageName_B;
548        Data.Civ2_Time=1;
549        Data.Civ2_Dt=1;
[598]550        for ilist=1:length(list_param)
[606]551            Data.(Civ2_param{4+ilist})=Param.ActionInput.Civ2.(list_param{ilist});
[598]552        end
[606]553        Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ2_param];
554       
[598]555        nbvar=numel(Data.ListVarName);
556        Data.ListVarName=[Data.ListVarName {'Civ2_X','Civ2_Y','Civ2_U','Civ2_V','Civ2_F','Civ2_C'}];%  cell array containing the names of the fields to record
557        Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2'}];
558        Data.VarAttribute{nbvar+1}.Role='coord_x';
559        Data.VarAttribute{nbvar+2}.Role='coord_y';
560        Data.VarAttribute{nbvar+3}.Role='vector_x';
561        Data.VarAttribute{nbvar+4}.Role='vector_y';
562        Data.VarAttribute{nbvar+5}.Role='warnflag';
563        Data.Civ2_X=reshape(xtable,[],1);
564        Data.Civ2_Y=reshape(size(par_civ2.ImageA,1)-ytable+1,[],1);
565        Data.Civ2_U=reshape(utable,[],1);
566        Data.Civ2_V=reshape(-vtable,[],1);
567        Data.Civ2_C=reshape(ctable,[],1);
568        Data.Civ2_F=reshape(F,[],1);
569        Data.CivStage=Data.CivStage+1;
570    end
571   
572    %% Fix2
573    if isfield (Param.ActionInput,'Fix2')
574        ListFixParam=fieldnames(Param.ActionInput.Fix2);
575        for ilist=1:length(ListFixParam)
576            ParamName=ListFixParam{ilist};
577            ListName=['Fix2_' ParamName];
578            eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
579            eval(['Data.' ListName '=Param.ActionInput.Fix2.' ParamName ';'])
580        end
581        if check_civx
582            if ~isfield(Data,'fix2')
583                Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix2'];
584                Data.fix2=1;
585                Data.ListVarName=[Data.ListVarName {'vec2_FixFlag'}];
586                Data.VarDimName=[Data.VarDimName {'nb_vectors2'}];
587            end
588            Data.vec_FixFlag=fix(Param.Fix2,Data.vec2_F,Data.vec2_C,Data.vec2_U,Data.vec2_V,Data.vec2_X,Data.vec2_Y);
[597]589        else
[598]590            Data.ListVarName=[Data.ListVarName {'Civ2_FF'}];
591            Data.VarDimName=[Data.VarDimName {'nb_vec_2'}];
592            nbvar=length(Data.ListVarName);
593            Data.VarAttribute{nbvar}.Role='errorflag';
594            Data.Civ2_FF=fix(Param.ActionInput.Fix2,Data.Civ2_F,Data.Civ2_C,Data.Civ2_U,Data.Civ2_V);
595            Data.CivStage=Data.CivStage+1;
[597]596        end
[598]597       
598    end
599   
600    %% Patch2
601    if isfield (Param.ActionInput,'Patch2')
602        Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch2_Rho','Patch2_Threshold','Patch2_SubDomain'}];
603        Data.Patch2_FieldSmooth=Param.ActionInput.Patch2.FieldSmooth;
604        Data.Patch2_MaxDiff=Param.ActionInput.Patch2.MaxDiff;
605        Data.Patch2_SubDomainSize=Param.ActionInput.Patch2.SubDomainSize;
606        nbvar=length(Data.ListVarName);
607        Data.ListVarName=[Data.ListVarName {'Civ2_U_smooth','Civ2_V_smooth','Civ2_SubRange','Civ2_NbCentres','Civ2_Coord_tps','Civ2_U_tps','Civ2_V_tps'}];
608        Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2',{'nb_coord','nb_bounds','nb_subdomain_2'},{'nb_subdomain_2'},...
609            {'nb_tps_2','nb_coord','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'}}];
610       
611        Data.VarAttribute{nbvar+1}.Role='vector_x';
612        Data.VarAttribute{nbvar+2}.Role='vector_y';
613        Data.VarAttribute{nbvar+5}.Role='coord_tps';
614        Data.VarAttribute{nbvar+6}.Role='vector_x';
615        Data.VarAttribute{nbvar+7}.Role='vector_y';
616        Data.Civ2_U_smooth=zeros(size(Data.Civ2_X));
617        Data.Civ2_V_smooth=zeros(size(Data.Civ2_X));
618        if isfield(Data,'Civ2_FF')
619            ind_good=find(Data.Civ2_FF==0);
[597]620        else
[598]621            ind_good=1:numel(Data.Civ2_X);
[597]622        end
[598]623        [Data.Civ2_SubRange,Data.Civ2_NbCentres,Data.Civ2_Coord_tps,Data.Civ2_U_tps,Data.Civ2_V_tps,tild,Ures, Vres,tild,FFres]=...
624            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);
625        Data.Civ2_U_smooth(ind_good)=Ures;
626        Data.Civ2_V_smooth(ind_good)=Vres;
627        Data.Civ2_FF(ind_good)=FFres;
628        Data.CivStage=Data.CivStage+1;
[597]629    end
[598]630   
631    %% write result in a netcdf file if requested
632    if exist('ncfile','var')
633        errormsg=struct2nc(ncfile,Data);
634        if isempty(errormsg)
635            disp([ncfile ' written'])
636        else
637            disp(errormsg)
638        end
639    end
[597]640end
641
[598]642% 'civ': function piv.m adapted from PIVlab http://pivlab.blogspot.com/
643%--------------------------------------------------------------------------
644% function [xtable ytable utable vtable typevector] = civ (image1,image2,ibx,iby step, subpixfinder, mask, roi)
645%
646% OUTPUT:
647% xtable: set of x coordinates
648% ytable: set of y coordiantes
649% utable: set of u displacements (along x)
650% vtable: set of v displacements (along y)
651% ctable: max image correlation for each vector
652% typevector: set of flags, =1 for good, =0 for NaN vectors
653%
654%INPUT:
655% par_civ: structure of input parameters, with fields:
656%  .CorrBoxSize
657%  .SearchBoxSize
658%  .SearchBoxShift
659%  .ImageHeight
660%  .ImageWidth
661%  .Dx, Dy
662%  .Grid
663%  .Mask
664%  .MinIma
665%  .MaxIma
666%  .image1:first image (matrix)
667% image2: second image (matrix)
668% ibx2,iby2: half size of the correlation box along x and y, in px (size=(2*iby2+1,2*ibx2+1)
669% isx2,isy2: half size of the search box along x and y, in px (size=(2*isy2+1,2*isx2+1)
670% shiftx, shifty: shift of the search box (in pixel index, yshift reversed)
671% step: mesh of the measurement points (in px)
672% subpixfinder=1 or 2 controls the curve fitting of the image correlation
673% mask: =[] for no mask
674% roi: 4 element vector defining a region of interest: x position, y position, width, height, (in image indices), for the whole image, roi=[];
675function [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ)
676%this funtion performs the DCC PIV analysis. Recent window-deformation
677%methods perform better and will maybe be implemented in the future.
678
679%% prepare measurement grid
680if isfield(par_civ,'Grid')% grid points set as input
681    if ischar(par_civ.Grid)%read the drid file if the input is a file name
682        par_civ.Grid=dlmread(par_civ.Grid);
683        par_civ.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
684    end
685else% automatic grid
686    minix=floor(par_civ.Dx/2)-0.5;
687    maxix=minix+par_civ.Dx*floor((par_civ.ImageWidth-1)/par_civ.Dx);
688    miniy=floor(par_civ.Dy/2)-0.5;
689    maxiy=minix+par_civ.Dy*floor((par_civ.ImageHeight-1)/par_civ.Dy);
690    [GridX,GridY]=meshgrid(minix:par_civ.Dx:maxix,miniy:par_civ.Dy:maxiy);
691    par_civ.Grid(:,1)=reshape(GridX,[],1);
692    par_civ.Grid(:,2)=reshape(GridY,[],1);
[597]693end
[598]694nbvec=size(par_civ.Grid,1);
695
696%% prepare correlation and search boxes
697ibx2=ceil(par_civ.CorrBoxSize(1)/2);
698iby2=ceil(par_civ.CorrBoxSize(2)/2);
699isx2=ceil(par_civ.SearchBoxSize(1)/2);
700isy2=ceil(par_civ.SearchBoxSize(2)/2);
701shiftx=round(par_civ.SearchBoxShift(:,1));
702shifty=-round(par_civ.SearchBoxShift(:,2));% sign minus because image j index increases when y decreases
703if numel(shiftx)==1% case of a unique shift for the whole field( civ1)
704    shiftx=shiftx*ones(nbvec,1);
705    shifty=shifty*ones(nbvec,1);
706end
707
708%% Default output
709xtable=par_civ.Grid(:,1);
710ytable=par_civ.Grid(:,2);
711utable=zeros(nbvec,1);
712vtable=zeros(nbvec,1);
713ctable=zeros(nbvec,1);
714F=zeros(nbvec,1);
715result_conv=[];
716errormsg='';
717
718%% prepare mask
719if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
720    if strcmp(par_civ.Mask,'all')
721        return    % get the grid only, no civ calculation
722    elseif ischar(par_civ.Mask)
723        par_civ.Mask=imread(par_civ.Mask);
724    end
725end
726check_MinIma=isfield(par_civ,'MinIma');% test for image luminosity threshold
727check_MaxIma=isfield(par_civ,'MaxIma') && ~isempty(par_civ.MaxIma);
728
729% %% prepare images
730% if isfield(par_civ,'reverse_pair')
731%     if par_civ.reverse_pair
732%         if ischar(par_civ.ImageB)
733%             temp=par_civ.ImageA;
734%             par_civ.ImageA=imread(par_civ.ImageB);
735%         end
736%         if ischar(temp)
737%             par_civ.ImageB=imread(temp);
738%         end
739%     end
740% else
741%     if ischar(par_civ.ImageA)
742%         par_civ.ImageA=imread(par_civ.ImageA);
743%     end
744%     if ischar(par_civ.ImageB)
745%         par_civ.ImageB=imread(par_civ.ImageB);
746%     end
747% end
748par_civ.ImageA=sum(double(par_civ.ImageA),3);%sum over rgb component for color images
749par_civ.ImageB=sum(double(par_civ.ImageB),3);
750[npy_ima npx_ima]=size(par_civ.ImageA);
751if ~isequal(size(par_civ.ImageB),[npy_ima npx_ima])
752    errormsg='image pair with unequal size';
[597]753    return
754end
755
[598]756%% Apply mask
757    % Convention for mask IDEAS TO IMPLEMENT ?
758    % mask >200 : velocity calculated
759    %  200 >=mask>150;velocity not calculated, interpolation allowed (bad spots)
760    % 150>=mask >100: velocity not calculated, nor interpolated
761    %  100>=mask> 20: velocity not calculated, impermeable (no flux through mask boundaries)
762    %  20>=mask: velocity=0
763checkmask=0;
764MinA=min(min(par_civ.ImageA));
765MinB=min(min(par_civ.ImageB));
766if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
767   checkmask=1;
768   if ~isequal(size(par_civ.Mask),[npy_ima npx_ima])
769        errormsg='mask must be an image with the same size as the images';
770        return
771   end
772  %  check_noflux=(par_civ.Mask<100) ;%TODO: to implement
773    check_undefined=(par_civ.Mask<200 & par_civ.Mask>=20 );
774    par_civ.ImageA(check_undefined)=MinA;% put image A to zero (i.e. the min image value) in the undefined  area
775    par_civ.ImageB(check_undefined)=MinB;% put image B to zero (i.e. the min image value) in the undefined  area
776end
777
778%% compute image correlations: MAINLOOP on velocity vectors
779corrmax=0;
780sum_square=1;% default
781mesh=1;% default
782CheckDecimal=isfield(par_civ,'CheckDecimal')&& par_civ.CheckDecimal==1;
783if CheckDecimal
784    mesh=0.2;%mesh in pixels for subpixel image interpolation
785    CheckDeformation=isfield(par_civ,'CheckDeformation')&& par_civ.CheckDeformation==1;
786end
787% vector=[0 0];%default
788for ivec=1:nbvec
789    iref=round(par_civ.Grid(ivec,1)+0.5);% xindex on the image A for the middle of the correlation box
790    jref=round(par_civ.ImageHeight-par_civ.Grid(ivec,2)+0.5);% yindex on the image B for the middle of the correlation box
791    %if ~(checkmask && par_civ.Mask(jref,iref)<=20) %velocity not set to zero by the black mask
792    %         if jref-iby2<1 || jref+iby2>par_civ.ImageHeight|| iref-ibx2<1 || iref+ibx2>par_civ.ImageWidth||...
793    %               jref+shifty(ivec)-isy2<1||jref+shifty(ivec)+isy2>par_civ.ImageHeight|| iref+shiftx(ivec)-isx2<1 || iref+shiftx(ivec)+isx2>par_civ.ImageWidth  % we are outside the image
794    %             F(ivec)=3;
795    %         else
796    F(ivec)=0;
797    subrange1_x=iref-ibx2:iref+ibx2;% x indices defining the first subimage
798    subrange1_y=jref-iby2:jref+iby2;% y indices defining the first subimage
799    subrange2_x=iref+shiftx(ivec)-isx2:iref+shiftx(ivec)+isx2;%x indices defining the second subimage
800    subrange2_y=jref+shifty(ivec)-isy2:jref+shifty(ivec)+isy2;%y indices defining the second subimage
801    image1_crop=MinA*ones(numel(subrange1_y),numel(subrange1_x));% default value=min of image A
802    image2_crop=MinA*ones(numel(subrange2_y),numel(subrange2_x));% default value=min of image A
803    check1_x=subrange1_x>=1 & subrange1_x<=par_civ.ImageWidth;% check which points in the subimage 1 are contained in the initial image 1
804    check1_y=subrange1_y>=1 & subrange1_y<=par_civ.ImageHeight;
805    check2_x=subrange2_x>=1 & subrange2_x<=par_civ.ImageWidth;% check which points in the subimage 2 are contained in the initial image 2
806    check2_y=subrange2_y>=1 & subrange2_y<=par_civ.ImageHeight;
807   
808    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
809    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
810    image1_mean=mean(mean(image1_crop));
811    image2_mean=mean(mean(image2_crop));
812    %threshold on image minimum
813    if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
814        F(ivec)=3;
[597]815    end
[598]816    %threshold on image maximum
817    if check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
818        F(ivec)=3;
[597]819    end
[598]820    %         end
821    if F(ivec)~=3
822        image1_crop=image1_crop-image1_mean;%substract the mean
823        image2_crop=image2_crop-image2_mean;
824        if CheckDecimal
825            xi=(1:mesh:size(image1_crop,2));
826            yi=(1:mesh:size(image1_crop,1))';
827            if CheckDeformation
828                [XI,YI]=meshgrid(xi-ceil(size(image1_crop,2)/2),yi-ceil(size(image1_crop,1)/2));
829                XIant=XI-par_civ.DUDX(ivec)*XI-par_civ.DUDY(ivec)*YI+ceil(size(image1_crop,2)/2);
830                YIant=YI-par_civ.DVDX(ivec)*XI-par_civ.DVDY(ivec)*YI+ceil(size(image1_crop,1)/2);
831                image1_crop=interp2(image1_crop,XIant,YIant);
832            else
833                image1_crop=interp2(image1_crop,xi,yi);
[597]834            end
[598]835            xi=(1:mesh:size(image2_crop,2));
836            yi=(1:mesh:size(image2_crop,1))';
837            image2_crop=interp2(image2_crop,xi,yi);
[597]838        end
[598]839        sum_square=sum(sum(image1_crop.*image1_crop));
840        %reference: Oliver Pust, PIV: Direct Cross-Correlation
841        result_conv= conv2(image2_crop,flipdim(flipdim(image1_crop,2),1),'valid');
842        corrmax= max(max(result_conv));
843        result_conv=(result_conv/corrmax)*255; %normalize, peak=always 255
844        %Find the correlation max, at 255
845        [y,x] = find(result_conv==255,1);
846        if ~isempty(y) && ~isempty(x)
847            try
848                if par_civ.CorrSmooth==1
849                    [vector,F(ivec)] = SUBPIXGAUSS (result_conv,x,y);
850                elseif par_civ.CorrSmooth==2
851                    [vector,F(ivec)] = SUBPIX2DGAUSS (result_conv,x,y);
[597]852                end
[598]853                utable(ivec)=vector(1)*mesh+shiftx(ivec);
854                vtable(ivec)=vector(2)*mesh+shifty(ivec);
855                xtable(ivec)=iref+utable(ivec)/2-0.5;% convec flow (velocity taken at the point middle from imgae 1 and 2)
856                ytable(ivec)=jref+vtable(ivec)/2-0.5;% and position of pixel 1=0.5 (convention for image coordinates=0 at the edge)
857                iref=round(xtable(ivec));% image index for the middle of the vector
858                jref=round(ytable(ivec));
859                if checkmask && par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100
860                    utable(ivec)=0;
861                    vtable(ivec)=0;
862                    F(ivec)=3;
863                end
864                ctable(ivec)=corrmax/sum_square;% correlation value
865            catch ME
866                F(ivec)=3;
[597]867            end
[598]868        else
869            F(ivec)=3;
[597]870        end
[598]871    end
872end
873result_conv=result_conv*corrmax/(255*sum_square);% keep the last correlation matrix for output
874
875%------------------------------------------------------------------------
876% --- Find the maximum of the correlation function after interpolation
877function [vector,F] = SUBPIXGAUSS (result_conv,x,y)
878%------------------------------------------------------------------------
879vector=[0 0]; %default
880F=0;
881[npy,npx]=size(result_conv);
882
883% if (x <= (size(result_conv,1)-1)) && (y <= (size(result_conv,1)-1)) && (x >= 1) && (y >= 1)
884    %the following 8 lines are copyright (c) 1998, Uri Shavit, Roi Gurka, Alex Liberzon, Technion ï¿œ Israel Institute of Technology
885    %http://urapiv.wordpress.com
886    peaky = y;
887    if y <= npy-1 && y >= 1
888        f0 = log(result_conv(y,x));
889        f1 = real(log(result_conv(y-1,x)));
890        f2 = real(log(result_conv(y+1,x)));
891        peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
892    else
893        F=-2; % warning flag for vector truncated by the limited search box
894    end
895    peakx=x;
896    if x <= npx-1 && x >= 1
897        f0 = log(result_conv(y,x));
898        f1 = real(log(result_conv(y,x-1)));
899        f2 = real(log(result_conv(y,x+1)));
900        peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
901    else
902        F=-2; % warning flag for vector truncated by the limited search box
903    end
904    vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
905
906%------------------------------------------------------------------------
907% --- Find the maximum of the correlation function after interpolation
908function [vector,F] = SUBPIX2DGAUSS (result_conv,x,y)
909%------------------------------------------------------------------------
910vector=[0 0]; %default
911F=-2;
912peaky=y;
913peakx=x;
914[npy,npx]=size(result_conv);
915if (x <= npx-1) && (y <= npy-1) && (x >= 1) && (y >= 1)
916    F=0;
917    for i=-1:1
918        for j=-1:1
919            %following 15 lines based on
920            %H. Nobach ï¿œ M. Honkanen (2005)
921            %Two-dimensional Gaussian regression for sub-pixel displacement
922            %estimation in particle image velocimetry or particle position
923            %estimation in particle tracking velocimetry
924            %Experiments in Fluids (2005) 38: 511ï¿œ515
925            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
926            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
927            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
928            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
929            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
930        end
931    end
932    c10=(1/6)*sum(sum(c10));
933    c01=(1/6)*sum(sum(c01));
934    c11=(1/4)*sum(sum(c11));
935    c20=(1/6)*sum(sum(c20));
936    c02=(1/6)*sum(sum(c02));
937    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11^2);
938    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11^2);
939    if abs(deltax)<1
940        peakx=x+deltax;
941    end
942    if abs(deltay)<1
943        peaky=y+deltay;
944    end
945end
946vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
947
948%'RUN_FIX': function for fixing velocity fields:
949%-----------------------------------------------
950% RUN_FIX(filename,field,flagindex,thresh_vecC,thresh_vel,iter,flag_mask,maskname,fileref,fieldref)
951%
952%filename: name of the netcdf file (used as input and output)
953%field: structure specifying the names of the fields to fix (depending on civ1 or civ2)
954    %.vel_type='civ1' or 'civ2';
955    %.nb=name of the dimension common to the field to fix ('nb_vectors' for civ1);
956    %.fixflag=name of fix flag variable ('vec_FixFlag' for civ1)
957%flagindex: flag specifying which values of vec_f are removed:
958        % if flagindex(1)=1: vec_f=-2 vectors are removed
959        % if flagindex(2)=1: vec_f=3 vectors are removed
960        % if flagindex(3)=1: vec_f=2 vectors are removed (if iter=1) or vec_f=4 vectors are removed (if iter=2)
961%iter=1 for civ1 fields and iter=2 for civ2 fields
962%thresh_vecC: threshold in the image correlation vec_C
963%flag_mask: =1 mask used to remove vectors (0 else)
964%maskname: name of the mask image file for fix
965%thresh_vel: threshold on velocity, or on the difference with the reference file fileref if exists
966%inf_sup=1: remove values smaller than threshold thresh_vel, =2, larger than threshold
967%fileref: .nc file name for a reference velocity (='': refrence 0 used)
968%fieldref: 'civ1','filter1'...feld used in fileref
969
970function FF=fix(Param,F,C,U,V,X,Y)
971FF=zeros(size(F));%default
972
973%criterium on warn flags
974FlagName={'CheckFmin2','CheckF2','CheckF3','CheckF4'};
975FlagVal=[-2 2 3 4];
976for iflag=1:numel(FlagName)
977    if isfield(Param,FlagName{iflag}) && Param.(FlagName{iflag})
978        FF=(FF==1| F==FlagVal(iflag));
979    end
980end
981%criterium on correlation values
982if isfield (Param,'MinCorr')
983    FF=FF==1 | C<Param.MinCorr;
984end
985if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
986    Umod= U.*U+V.*V;
987    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
988        FF=FF==1 | Umod<(Param.MinVel*Param.MinVel);
989    end
990    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
991        FF=FF==1 | Umod>(Param.MaxVel*Param.MaxVel);
992    end
993end
994
995
996%------------------------------------------------------------------------
997% --- determine the list of index pairs of processing file
998function [i1_series,i2_series,j1_series,j2_series,check_bounds,NomTypeNc]=...
[635]999    find_pair_indices(str_civ,i_series,j_series,MinIndex_i,MaxIndex_i,MinIndex_j,MaxIndex_j)
[598]1000%------------------------------------------------------------------------
[610]1001i1_series=i_series;% set of first image indexes
[598]1002i2_series=i_series;
1003j1_series=ones(size(i_series));% set of first image numbers
1004j2_series=ones(size(i_series));
[610]1005r=regexp(str_civ,'^\D(?<ind>[i|j])=( -| )(?<num1>\d+)\|(?<num2>\d+)','names');
[598]1006if ~isempty(r)
1007    mode=['D' r.ind];
1008    ind1=str2num(r.num1);
1009    ind2=str2num(r.num2);
1010else
[668]1011    mode='j1-j2';
[598]1012    r=regexp(str_civ,'^j= (?<num1>[a-z])-(?<num2>[a-z])','names');
1013    if ~isempty(r)
1014        NomTypeNc='_1ab';
1015    else
1016        r=regexp(str_civ,'^j= (?<num1>[A-Z])-(?<num2>[A-Z])','names');
1017        if ~isempty(r)
1018            NomTypeNc='_1AB';
[597]1019        else
[598]1020            r=regexp(str_civ,'^j= (?<num1>\d+)-(?<num2>\d+)','names');
1021            if ~isempty(r)
1022                NomTypeNc='_1_1-2';
1023            end           
[597]1024        end
1025    end
[598]1026    if isempty(r)
1027        display('wrong pair mode input option')
1028    else
1029    ind1=stra2num(r.num1);
1030    ind2=stra2num(r.num2);
1031    end
[597]1032end
[598]1033if strcmp (mode,'Di')
1034    i1_series=i_series-ind1;% set of first image numbers
1035    i2_series=i_series+ind2;
[635]1036     check_bounds=i1_series<MinIndex_i | i2_series>MaxIndex_i;
[598]1037    if isempty(j_series)
1038        NomTypeNc='_1-2';
1039    else
[601]1040        j1_series=j_series;
1041        j2_series=j_series;
[598]1042        NomTypeNc='_1-2_1';
1043    end
1044elseif strcmp (mode,'Dj')
1045    j1_series=j_series-ind1;
1046    j2_series=j_series+ind2;
[635]1047    check_bounds=j1_series<MinIndex_j | j2_series>MaxIndex_j;
[598]1048    NomTypeNc='_1_1-2';
1049else  %bursts
[668]1050    i1_series=i_series(1,:);% do not sweep the j index
1051    i2_series=i_series(1,:);
1052    j1_series=ind1*ones(1,size(i_series,2));% j index is fixed by pair choice
1053    j2_series=ind2*ones(1,size(i_series,2));
1054    check_bounds=zeros(size(i1_series));% no limitations due to min-max indices
[598]1055end
[597]1056
[598]1057
1058
1059
Note: See TracBrowser for help on using the repository browser.