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

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

various bugs corrected after tests with Windows OS.

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