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

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