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

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

error messages improved

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