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

Last change on this file since 743 was 736, checked in by sommeria, 11 years ago

various corrections

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