source: trunk/src/civ_matlab.m @ 772

Last change on this file since 772 was 772, checked in by sommeria, 10 years ago

manip corrections and cleaning

File size: 34.8 KB
Line 
1%'civ_matlab': main PIV function, calleed by the GUI civ
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_matlab(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_matlab(Param,ncfile)
41errormsg='';
42Data.ListGlobalAttribute={'Conventions','Program','CivStage'};
43Data.Conventions='uvmat/civdata';% states the conventions used for the description of field variables and attributes
44Data.Program='civ_matlab';
45Data.CivStage=0;%default
46ListVarCiv1={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F'}; %variables to read
47ListVarFix1={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F','Civ1_FF'};
48mask='';
49maskname='';%default
50check_civx=0;%default
51check_civ1=0;%default
52check_patch1=0;%default
53
54% case of input Param set by an xml file (batch mode)
55if ischar(Param)
56    Param=xml2struct(Param); %if Param is the name of an xml file, read this file as a Matlab structure
57end
58
59%% Civ1
60if isfield (Param,'Civ1')
61    par_civ1=Param.Civ1;
62    if isfield(Param.Civ1,'ImageA') && ischar(Param.Civ1.ImageA)% the input is a char string, read the corresponding image name (else  Param.Civ1.ImageA is already an image)
63        Param.Civ1.ImageA=regexprep(Param.Civ1.ImageA,'''','\');
64        [par_civ1.ImageA,VideoObject] = read_image(Param.Civ1.ImageA,par_civ1.FileTypeA,[],par_civ1.FrameIndexA);
65    end
66    if isfield(Param.Civ1,'ImageB')&& ischar(Param.Civ1.ImageB)% the input is a char string, read the corresponding image name (else  Param.Civ1.ImageB is already an image)
67        Param.Civ1.ImageB=regexprep(Param.Civ1.ImageB,'''','\');
68        if strcmp(Param.Civ1.ImageA,Param.Civ1.ImageB)% use the same movie object
69            [par_civ1.ImageB,VideoObject] = read_image(Param.Civ1.ImageB,par_civ1.FileTypeB,VideoObject,par_civ1.FrameIndexB);
70        else
71            [par_civ1.ImageB,VideoObject] = read_image(Param.Civ1.ImageB,par_civ1.FileTypeB,par_civ1.ImageB,par_civ1.FrameIndexB);
72        end
73    end
74    list_param=(fieldnames(Param.Civ1))';
75    Civ1_param=list_param;%default
76   
77    %set the values of all the global attributes in list_param
78    for ilist=1:length(list_param)
79        Civ1_param{ilist}=['Civ1_' list_param{ilist}];
80        Data.(['Civ1_' list_param{ilist}])=Param.Civ1.(list_param{ilist});
81    end
82    Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ1_param];
83    Data.CivStage=1;
84   
85    % set the list of variables
86    Data.ListVarName={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_F','Civ1_C'};%  cell array containing the names of the fields to record
87    Data.VarDimName={'nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1','nb_vec_1'};
88    Data.VarAttribute{1}.Role='coord_x';
89    Data.VarAttribute{2}.Role='coord_y';
90    Data.VarAttribute{3}.Role='vector_x';
91    Data.VarAttribute{4}.Role='vector_y';
92    Data.VarAttribute{5}.Role='warnflag';
93   
94    if isfield(Param,'ListCompareMode') && strcmp(Param.ListCompareMode, 'PIV volume')
95        Data.ListVarName=[Data.ListVarName 'Civ1_Z'];
96        Data.Civ1_X=[];Data.Civ1_Y=[];Data.Civ1_Z=[];
97        Data.Civ1_U=[];Data.Civ1_V=[];Data.Civ1_C=[];Data.Civ1_F=[];
98        for ivol=1:NbSlice
99            % caluclate velocity data (y and v in indices, reverse to y component)
100            [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ1);
101            if ~isempty(errormsg)
102                return
103            end
104            Data.Civ1_X=[Data.Civ1_X reshape(xtable,[],1)];
105            Data.Civ1_Y=[Data.Civ1_Y reshape(Param.Civ1.ImageHeight-ytable+1,[],1)];
106            Data.Civ1_Z=[Data.Civ1_Z ivol*ones(numel(xtable),1)];% z=image index in image coordinates
107            Data.Civ1_U=[Data.Civ1_U reshape(utable,[],1)];
108            Data.Civ1_V=[Data.Civ1_V reshape(-vtable,[],1)];
109            Data.Civ1_C=[Data.Civ1_C reshape(ctable,[],1)];
110            Data.Civ1_F=[Data.Civ1_C reshape(F,[],1)];
111        end
112    else %usual PIV
113        % caluclate velocity data (y and v in indices, reverse to y component)
114        [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ1);
115        if ~isempty(errormsg)
116            return
117        end
118        Data.Civ1_X=reshape(xtable,[],1);
119        Data.Civ1_Y=reshape(Param.Civ1.ImageHeight-ytable+1,[],1);
120        Data.Civ1_U=reshape(utable,[],1);
121        Data.Civ1_V=reshape(-vtable,[],1);
122        Data.Civ1_C=reshape(ctable,[],1);
123        Data.Civ1_F=reshape(F,[],1);
124    end
125else
126    if exist('ncfile','var')
127        CivFile=ncfile;
128    elseif isfield(Param.Patch1,'CivFile')
129        CivFile=Param.Patch1.CivFile;
130    end
131    [Data,tild,tild,erromsg]=nc2struct(CivFile,'ListGlobalAttribute','absolut_time_T0'); %look for the constant 'absolut_time_T0' to detect old civx data format
132    if ~isempty(errormsg)
133        return
134    end
135    if ~isempty(Data.absolut_time_T0')%read civx file
136        check_civx=1;% test for old civx data format
137        [Data,vardetect,ichoice]=nc2struct(CivFile);%read the variables in the netcdf file
138    else
139        Data=nc2struct(CivFile);%read civ1 and fix1 data in the existing netcdf file
140    end
141end
142
143%% Fix1
144if isfield (Param,'Fix1')
145    ListFixParam=fieldnames(Param.Fix1);
146    for ilist=1:length(ListFixParam)
147        ParamName=ListFixParam{ilist};
148        ListName=['Fix1_' ParamName];
149        eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
150        eval(['Data.' ListName '=Param.Fix1.' ParamName ';'])
151    end
152    if check_civx
153        if ~isfield(Data,'fix')
154            Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix'];
155            Data.fix=1;
156            Data.ListVarName=[Data.ListVarName {'vec_FixFlag'}];
157            Data.VarDimName=[Data.VarDimName {'nb_vectors'}];
158        end
159        Data.vec_FixFlag=fix(Param.Fix1,Data.vec_F,Data.vec_C,Data.vec_U,Data.vec_V,Data.vec_X,Data.vec_Y);
160    else
161        Data.ListVarName=[Data.ListVarName {'Civ1_FF'}];
162        Data.VarDimName=[Data.VarDimName {'nb_vec_1'}];
163        nbvar=length(Data.ListVarName);
164        Data.VarAttribute{nbvar}.Role='errorflag';
165        Data.Civ1_FF=fix(Param.Fix1,Data.Civ1_F,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V);
166        Data.CivStage=2;
167    end
168end
169%% Patch1
170if isfield (Param,'Patch1')
171    if check_civx
172        errormsg='Civ Matlab input needed for patch';
173        return
174    end
175   
176    Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch1_Rho','Patch1_Threshold','Patch1_SubDomain'}];
177    Data.Patch1_FieldSmooth=Param.Patch1.FieldSmooth;
178    Data.Patch1_MaxDiff=Param.Patch1.MaxDiff;
179    Data.Patch1_SubDomainSize=Param.Patch1.SubDomainSize;
180    nbvar=length(Data.ListVarName);
181    Data.ListVarName=[Data.ListVarName {'Civ1_U_smooth','Civ1_V_smooth','Civ1_SubRange','Civ1_NbCentre','Civ1_Coord_tps','Civ1_U_tps','Civ1_V_tps'}];
182    Data.VarDimName=[Data.VarDimName {'nb_vec_1','nb_vec_1',{'nb_coord','nb_bound','nb_subdomain_1'},'nb_subdomain_1',...
183        {'nb_tps_1','nb_coord','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'},{'nb_tps_1','nb_subdomain_1'}}];
184    Data.VarAttribute{nbvar+1}.Role='vector_x';
185    Data.VarAttribute{nbvar+2}.Role='vector_y';
186    Data.VarAttribute{nbvar+5}.Role='coord_tps';
187    Data.VarAttribute{nbvar+6}.Role='vector_x';
188    Data.VarAttribute{nbvar+7}.Role='vector_y';
189    Data.Civ1_U_smooth=zeros(size(Data.Civ1_X));
190    Data.Civ1_V_smooth=zeros(size(Data.Civ1_X));
191    if isfield(Data,'Civ1_FF')
192        ind_good=find(Data.Civ1_FF==0);
193    else
194        ind_good=1:numel(Data.Civ1_X);
195    end
196    [Data.Civ1_SubRange,Data.Civ1_NbCentre,Data.Civ1_Coord_tps,Data.Civ1_U_tps,Data.Civ1_V_tps,tild,Ures, Vres,tild,FFres]=...
197        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);
198    Data.Civ1_U_smooth(ind_good)=Ures;
199    Data.Civ1_V_smooth(ind_good)=Vres;
200    Data.Civ1_FF(ind_good)=FFres;
201    Data.CivStage=3;
202end
203
204%% Civ2
205if isfield (Param,'Civ2')
206    par_civ2=Param.Civ2;
207    par_civ2.ImageA=[];
208    par_civ2.ImageB=[];
209    if isfield(Param.Civ2,'ImageA') && isfield(Param.Civ2,'ImageB')
210        Param.Civ2.ImageA=regexprep(Param.Civ2.ImageA,'''','\');
211        Param.Civ2.ImageB=regexprep(Param.Civ2.ImageB,'''','\');
212        if isfield (Param,'Civ1')
213            Param.Civ2.ImageA=regexprep(Param.Civ2.ImageA,'''','\');
214            if strcmp(Param.Civ1.ImageA,Param.Civ2.ImageA)
215                if isequal(Param.Civ1.FrameIndexA,Param.Civ2.FrameIndexA)
216                    par_civ2.ImageA=par_civ1.ImageA;
217                else % read another frame of the same movie object
218                    par_civ2.ImageA = read_image(Param.Civ2.ImageA,Param.Civ2.FileTypeA,VideoObject,Param.Civ2.FrameIndexA);
219                end
220            end
221            Param.Civ2.ImageB=regexprep(Param.Civ2.ImageB,'''','\');
222            if strcmp(Param.Civ1.ImageB,Param.Civ2.ImageB)
223                if isequal(Param.Civ1.FrameIndexB,Param.Civ2.FrameIndexB)
224                    par_civ2.ImageB=par_civ1.ImageB;
225                else % read another frame of the same movie object
226                    par_civ2.ImageB = read_image(Param.Civ2.ImageB,Param.Civ2.FileTypeB,VideoObject,Param.Civ2.FrameIndexB);
227                end
228            end
229        end
230        if isempty(par_civ2.ImageA) && isfield(Param.Civ2,'ImageA')
231            [par_civ2.ImageA,VideoObject] = read_image(Param.Civ2.ImageA,Param.Civ2.FileTypeA,[],Param.Civ2.FrameIndexA);
232        end
233        if isempty(par_civ2.ImageB)&& isfield(Param.Civ2,'ImageB')
234            if strcmp(Param.Civ2.ImageA,Param.Civ2.ImageB)
235                par_civ2.ImageB = read_image(Param.Civ2.ImageB,Param.Civ2.FileTypeB,VideoObject,Param.Civ2.FrameIndexB);
236            else
237                par_civ2.ImageB = read_image(Param.Civ2.ImageB,Param.Civ2.FileTypeB,[],Param.Civ2.FrameIndexB);
238            end
239        end
240    end
241    %     ibx2=ceil(par_civ2.CorrBoxSize(1)/2);
242    %     iby2=ceil(par_civ2.CorrBoxSize(2)/2);
243    %     isx2=ibx2+4;% search ara +-4 pixels around the guess
244    %     isy2=iby2+4;
245    %     % shift from par_civ2.filename_nc1
246    %     % shiftx=velocity interpolated at position
247    %     miniy=max(1+isy2,1+iby2);
248    %     minix=max(1+isx2,1+ibx2);
249    %     maxiy=min(size(par_civ2.ImageA,1)-isy2,size(par_civ2.ImageA,1)-iby2);
250    %     maxix=min(size(par_civ2.ImageA,2)-isx2,size(par_civ2.ImageA,2)-ibx2);
251    %     [GridX,GridY]=meshgrid(minix:par_civ2.Dx:maxix,miniy:par_civ2.Dy:maxiy);
252    %     GridX=reshape(GridX,[],1);
253    %     GridY=reshape(GridY,[],1);
254    if isfield(par_civ2,'Grid')% grid points set as input file
255        if ischar(par_civ2.Grid)%read the grid file if the input is a file name
256            par_civ2.Grid=dlmread(par_civ2.Grid);
257            par_civ2.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
258        end
259    else% automatic grid
260        minix=floor(par_civ2.Dx/2)-0.5;
261        maxix=minix+par_civ2.Dx*floor((par_civ2.ImageWidth-1)/par_civ2.Dx);
262        miniy=floor(par_civ2.Dy/2)-0.5;
263        maxiy=minix+par_civ2.Dy*floor((par_civ2.ImageHeight-1)/par_civ2.Dy);
264        [GridX,GridY]=meshgrid(minix:par_civ2.Dx:maxix,miniy:par_civ2.Dy:maxiy);
265        par_civ2.Grid(:,1)=reshape(GridX,[],1);
266        par_civ2.Grid(:,2)=reshape(GridY,[],1);
267    end
268    Shiftx=zeros(size(par_civ2.Grid,1),1);% shift expected from civ1 data
269    Shifty=zeros(size(par_civ2.Grid,1),1);
270    nbval=zeros(size(par_civ2.Grid,1),1);
271    if par_civ2.CheckDeformation
272        DUDX=zeros(size(par_civ2.Grid,1),1);
273        DUDY=zeros(size(par_civ2.Grid,1),1);
274        DVDX=zeros(size(par_civ2.Grid,1),1);
275        DVDY=zeros(size(par_civ2.Grid,1),1);
276    end
277    NbSubDomain=size(Data.Civ1_SubRange,3);
278    % get the guess from patch1
279    for isub=1:NbSubDomain
280        nbvec_sub=Data.Civ1_NbCentre(isub);
281        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));
282        epoints = [GridX(ind_sel) GridY(ind_sel)];% coordinates of interpolation sites
283        ctrs=Data.Civ1_Coord_tps(1:nbvec_sub,:,isub) ;%(=initial points) ctrs
284        nbval(ind_sel)=nbval(ind_sel)+1;% records the number of values for eacn interpolation point (in case of subdomain overlap)
285        EM = tps_eval(epoints,ctrs);
286        Shiftx(ind_sel)=Shiftx(ind_sel)+EM*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
287        Shifty(ind_sel)=Shifty(ind_sel)+EM*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
288        if par_civ2.CheckDeformation
289            [EMDX,EMDY] = tps_eval_dxy(epoints,ctrs);%2D matrix of distances between extrapolation points epoints and spline centres (=site points) ctrs
290            DUDX(ind_sel)=DUDX(ind_sel)+EMDX*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
291            DUDY(ind_sel)=DUDY(ind_sel)+EMDY*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
292            DVDX(ind_sel)=DVDX(ind_sel)+EMDX*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
293            DVDY(ind_sel)=DVDY(ind_sel)+EMDY*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
294        end
295    end
296    mask='';
297    if par_civ2.CheckMask&&~isempty(par_civ2.Mask)&& ~strcmp(maskname,par_civ2.Mask)% mask exist, not already read in civ1
298        mask=imread(par_civ2.Mask);
299    end
300    ibx2=ceil(par_civ2.CorrBoxSize(1)/2);
301    iby2=ceil(par_civ2.CorrBoxSize(2)/2);
302    %     isx2=ibx2+4;% search ara +-4 pixels around the guess
303    %     isy2=iby2+4;
304    par_civ2.SearchBoxSize(1)=2*ibx2+9;% search ara +-4 pixels around the guess
305    par_civ2.SearchBoxSize(2)=2*iby2+9;
306    %par_civ2.SearchBoxSize(1)=2*isx2+1;
307    %par_civ2.SearchBoxSize(2)=2*isy2+1;
308    par_civ2.SearchBoxShift=[Shiftx(nbval>=1)./nbval(nbval>=1) Shifty(nbval>=1)./nbval(nbval>=1)];
309    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
310    if par_civ2.CheckDeformation
311        par_civ2.DUDX=DUDX./nbval;
312        par_civ2.DUDY=DUDY./nbval;
313        par_civ2.DVDX=DVDX./nbval;
314        par_civ2.DVDY=DVDY./nbval;
315    end
316    % caluclate velocity data (y and v in indices, reverse to y component)
317    [xtable ytable utable vtable ctable F] = civ (par_civ2);
318    list_param=(fieldnames(Param.Civ2))';
319    list_remove={'pxcmx','pxcmy','npx','npy','gridflag','maskflag','term_a','term_b','T0'};
320    for ilist=1:length(list_remove)
321        index=strcmp(list_remove{ilist},list_param);
322        if ~isempty(find(index,1))
323            list_param(index)=[];
324        end
325    end
326    for ilist=1:length(list_param)
327        Civ2_param{ilist}=['Civ2_' list_param{ilist}];
328        eval(['Data.Civ2_' list_param{ilist} '=Param.Civ2.' list_param{ilist} ';'])
329    end
330    if isfield(Data,'Civ2_gridname') && strcmp(Data.Civ1_gridname(1:6),'noFile')
331        Data.Civ1_gridname='';
332    end
333    if isfield(Data,'Civ2_maskname') && strcmp(Data.Civ1_maskname(1:6),'noFile')
334        Data.Civ2_maskname='';
335    end
336    Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ2_param {'Civ2_Time','Civ2_Dt'}];
337    nbvar=numel(Data.ListVarName);
338    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
339    Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2','nb_vec_2'}];
340    Data.VarAttribute{nbvar+1}.Role='coord_x';
341    Data.VarAttribute{nbvar+2}.Role='coord_y';
342    Data.VarAttribute{nbvar+3}.Role='vector_x';
343    Data.VarAttribute{nbvar+4}.Role='vector_y';
344    Data.VarAttribute{nbvar+5}.Role='warnflag';
345    Data.Civ2_X=reshape(xtable,[],1);
346    Data.Civ2_Y=reshape(size(par_civ2.ImageA,1)-ytable+1,[],1);
347    Data.Civ2_U=reshape(utable,[],1);
348    Data.Civ2_V=reshape(-vtable,[],1);
349    Data.Civ2_C=reshape(ctable,[],1);
350    Data.Civ2_F=reshape(F,[],1);
351    Data.CivStage=Data.CivStage+1;
352end
353
354%% Fix2
355if isfield (Param,'Fix2')
356    ListFixParam=fieldnames(Param.Fix2);
357    for ilist=1:length(ListFixParam)
358        ParamName=ListFixParam{ilist};
359        ListName=['Fix2_' ParamName];
360        eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
361        eval(['Data.' ListName '=Param.Fix2.' ParamName ';'])
362    end
363    if check_civx
364        if ~isfield(Data,'fix2')
365            Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix2'];
366            Data.fix2=1;
367            Data.ListVarName=[Data.ListVarName {'vec2_FixFlag'}];
368            Data.VarDimName=[Data.VarDimName {'nb_vectors2'}];
369        end
370        Data.vec_FixFlag=fix(Param.Fix2,Data.vec2_F,Data.vec2_C,Data.vec2_U,Data.vec2_V,Data.vec2_X,Data.vec2_Y);
371    else
372        Data.ListVarName=[Data.ListVarName {'Civ2_FF'}];
373        Data.VarDimName=[Data.VarDimName {'nb_vec_2'}];
374        nbvar=length(Data.ListVarName);
375        Data.VarAttribute{nbvar}.Role='errorflag';
376        Data.Civ2_FF=fix(Param.Fix2,Data.Civ2_F,Data.Civ2_C,Data.Civ2_U,Data.Civ2_V);
377        Data.CivStage=Data.CivStage+1;
378    end
379   
380end
381
382%% Patch2
383if isfield (Param,'Patch2')
384    Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch2_Rho','Patch2_Threshold','Patch2_SubDomain'}];
385    Data.Patch2_FieldSmooth=Param.Patch2.FieldSmooth;
386    Data.Patch2_MaxDiff=Param.Patch2.MaxDiff;
387    Data.Patch2_SubDomainSize=Param.Patch2.SubDomainSize;
388    nbvar=length(Data.ListVarName);
389    Data.ListVarName=[Data.ListVarName {'Civ2_U_smooth','Civ2_V_smooth','Civ2_SubRange','Civ2_NbCentre','Civ2_Coord_tps','Civ2_U_tps','Civ2_V_tps'}];
390    Data.VarDimName=[Data.VarDimName {'nb_vec_2','nb_vec_2',{'nb_coord','nb_bound','nb_subdomain_2'},{'nb_subdomain_2'},...
391        {'nb_tps_2','nb_coord','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'},{'nb_tps_2','nb_subdomain_2'}}];
392   
393    Data.VarAttribute{nbvar+1}.Role='vector_x';
394    Data.VarAttribute{nbvar+2}.Role='vector_y';
395    Data.VarAttribute{nbvar+5}.Role='coord_tps';
396    Data.VarAttribute{nbvar+6}.Role='vector_x';
397    Data.VarAttribute{nbvar+7}.Role='vector_y';
398    Data.Civ2_U_smooth=zeros(size(Data.Civ2_X));
399    Data.Civ2_V_smooth=zeros(size(Data.Civ2_X));
400    if isfield(Data,'Civ2_FF')
401        ind_good=find(Data.Civ2_FF==0);
402    else
403        ind_good=1:numel(Data.Civ2_X);
404    end
405    [Data.Civ2_SubRange,Data.Civ2_NbCentre,Data.Civ2_Coord_tps,Data.Civ2_U_tps,Data.Civ2_V_tps,tild,Ures, Vres,tild,FFres]=...
406        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);
407    Data.Civ2_U_smooth(ind_good)=Ures;
408    Data.Civ2_V_smooth(ind_good)=Vres;
409    Data.Civ2_FF(ind_good)=FFres;
410    Data.CivStage=Data.CivStage+1;
411end
412
413%% write result in a netcdf file if requested
414if exist('ncfile','var')
415    errormsg=struct2nc(ncfile,Data);
416    if isempty(errormsg)
417        disp([ncfile ' written'])
418    else
419        disp(errormsg)
420    end
421end
422
423% 'civ': function piv.m adapted from PIVlab http://pivlab.blogspot.com/
424%--------------------------------------------------------------------------
425% function [xtable ytable utable vtable typevector] = civ (image1,image2,ibx,iby step, subpixfinder, mask, roi)
426%
427% OUTPUT:
428% xtable: set of x coordinates
429% ytable: set of y coordiantes
430% utable: set of u displacements (along x)
431% vtable: set of v displacements (along y)
432% ctable: max image correlation for each vector
433% typevector: set of flags, =1 for good, =0 for NaN vectors
434%
435%INPUT:
436% par_civ: structure of input parameters, with fields:
437%  .CorrBoxSize
438%  .SearchBoxSize
439%  .SearchBoxShift
440%  .ImageHeight
441%  .ImageWidth
442%  .Dx, Dy
443%  .Grid
444%  .Mask
445%  .MinIma
446%  .MaxIma
447%  .image1:first image (matrix)
448% image2: second image (matrix)
449% ibx2,iby2: half size of the correlation box along x and y, in px (size=(2*iby2+1,2*ibx2+1)
450% isx2,isy2: half size of the search box along x and y, in px (size=(2*isy2+1,2*isx2+1)
451% shiftx, shifty: shift of the search box (in pixel index, yshift reversed)
452% step: mesh of the measurement points (in px)
453% subpixfinder=1 or 2 controls the curve fitting of the image correlation
454% mask: =[] for no mask
455% roi: 4 element vector defining a region of interest: x position, y position, width, height, (in image indices), for the whole image, roi=[];
456function [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ)
457%this funtion performs the DCC PIV analysis. Recent window-deformation
458%methods perform better and will maybe be implemented in the future.
459
460%% prepare measurement grid
461if isfield(par_civ,'Grid')% grid points set as input
462    if ischar(par_civ.Grid)%read the drid file if the input is a file name
463        par_civ.Grid=dlmread(par_civ.Grid);
464        par_civ.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
465    end
466else% automatic grid
467    minix=floor(par_civ.Dx/2)-0.5;
468    maxix=minix+par_civ.Dx*floor((par_civ.ImageWidth-1)/par_civ.Dx);
469    miniy=floor(par_civ.Dy/2)-0.5;
470    maxiy=minix+par_civ.Dy*floor((par_civ.ImageHeight-1)/par_civ.Dy);
471    [GridX,GridY]=meshgrid(minix:par_civ.Dx:maxix,miniy:par_civ.Dy:maxiy);
472    par_civ.Grid(:,1)=reshape(GridX,[],1);
473    par_civ.Grid(:,2)=reshape(GridY,[],1);
474end
475nbvec=size(par_civ.Grid,1);
476
477%% prepare correlation and search boxes
478ibx2=ceil(par_civ.CorrBoxSize(1)/2);
479iby2=ceil(par_civ.CorrBoxSize(2)/2);
480isx2=ceil(par_civ.SearchBoxSize(1)/2);
481isy2=ceil(par_civ.SearchBoxSize(2)/2);
482shiftx=round(par_civ.SearchBoxShift(:,1));
483shifty=-round(par_civ.SearchBoxShift(:,2));% sign minus because image j index increases when y decreases
484if numel(shiftx)==1% case of a unique shift for the whole field( civ1)
485    shiftx=shiftx*ones(nbvec,1);
486    shifty=shifty*ones(nbvec,1);
487end
488
489%% Default output
490xtable=par_civ.Grid(:,1);
491ytable=par_civ.Grid(:,2);
492utable=zeros(nbvec,1);
493vtable=zeros(nbvec,1);
494ctable=zeros(nbvec,1);
495F=zeros(nbvec,1);
496result_conv=[];
497errormsg='';
498
499%% prepare mask
500if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
501    if strcmp(par_civ.Mask,'all')
502        return    % get the grid only, no civ calculation
503    elseif ischar(par_civ.Mask)
504        par_civ.Mask=imread(par_civ.Mask);
505    end
506end
507check_MinIma=isfield(par_civ,'MinIma');% test for image luminosity threshold
508check_MaxIma=isfield(par_civ,'MaxIma') && ~isempty(par_civ.MaxIma);
509
510% %% prepare images
511% if isfield(par_civ,'reverse_pair')
512%     if par_civ.reverse_pair
513%         if ischar(par_civ.ImageB)
514%             temp=par_civ.ImageA;
515%             par_civ.ImageA=imread(par_civ.ImageB);
516%         end
517%         if ischar(temp)
518%             par_civ.ImageB=imread(temp);
519%         end
520%     end
521% else
522%     if ischar(par_civ.ImageA)
523%         par_civ.ImageA=imread(par_civ.ImageA);
524%     end
525%     if ischar(par_civ.ImageB)
526%         par_civ.ImageB=imread(par_civ.ImageB);
527%     end
528% end
529par_civ.ImageA=sum(double(par_civ.ImageA),3);%sum over rgb component for color images
530par_civ.ImageB=sum(double(par_civ.ImageB),3);
531[npy_ima npx_ima]=size(par_civ.ImageA);
532if ~isequal(size(par_civ.ImageB),[npy_ima npx_ima])
533    errormsg='image pair with unequal size';
534    return
535end
536
537%% Apply mask
538    % Convention for mask IDEAS TO IMPLEMENT ?
539    % mask >200 : velocity calculated
540    %  200 >=mask>150;velocity not calculated, interpolation allowed (bad spots)
541    % 150>=mask >100: velocity not calculated, nor interpolated
542    %  100>=mask> 20: velocity not calculated, impermeable (no flux through mask boundaries)
543    %  20>=mask: velocity=0
544checkmask=0;
545MinA=min(min(par_civ.ImageA));
546MinB=min(min(par_civ.ImageB));
547if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
548   checkmask=1;
549   if ~isequal(size(par_civ.Mask),[npy_ima npx_ima])
550        errormsg='mask must be an image with the same size as the images';
551        return
552   end
553  %  check_noflux=(par_civ.Mask<100) ;%TODO: to implement
554    check_undefined=(par_civ.Mask<200 & par_civ.Mask>=20 );
555    par_civ.ImageA(check_undefined)=MinA;% put image A to zero (i.e. the min image value) in the undefined  area
556    par_civ.ImageB(check_undefined)=MinB;% put image B to zero (i.e. the min image value) in the undefined  area
557end
558
559%% compute image correlations: MAINLOOP on velocity vectors
560corrmax=0;
561sum_square=1;% default
562mesh=1;% default
563CheckDecimal=isfield(par_civ,'CheckDecimal')&& par_civ.CheckDecimal==1;
564if CheckDecimal
565    mesh=0.2;%mesh in pixels for subpixel image interpolation
566    CheckDeformation=isfield(par_civ,'CheckDeformation')&& par_civ.CheckDeformation==1;
567end
568% vector=[0 0];%default
569for ivec=1:nbvec
570    iref=round(par_civ.Grid(ivec,1)+0.5);% xindex on the image A for the middle of the correlation box
571    jref=round(par_civ.ImageHeight-par_civ.Grid(ivec,2)+0.5);% yindex on the image B for the middle of the correlation box
572    %if ~(checkmask && par_civ.Mask(jref,iref)<=20) %velocity not set to zero by the black mask
573    %         if jref-iby2<1 || jref+iby2>par_civ.ImageHeight|| iref-ibx2<1 || iref+ibx2>par_civ.ImageWidth||...
574    %               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
575    %             F(ivec)=3;
576    %         else
577    F(ivec)=0;
578    subrange1_x=iref-ibx2:iref+ibx2;% x indices defining the first subimage
579    subrange1_y=jref-iby2:jref+iby2;% y indices defining the first subimage
580    subrange2_x=iref+shiftx(ivec)-isx2:iref+shiftx(ivec)+isx2;%x indices defining the second subimage
581    subrange2_y=jref+shifty(ivec)-isy2:jref+shifty(ivec)+isy2;%y indices defining the second subimage
582    image1_crop=MinA*ones(numel(subrange1_y),numel(subrange1_x));% default value=min of image A
583    image2_crop=MinA*ones(numel(subrange2_y),numel(subrange2_x));% default value=min of image A
584    check1_x=subrange1_x>=1 & subrange1_x<=par_civ.ImageWidth;% check which points in the subimage 1 are contained in the initial image 1
585    check1_y=subrange1_y>=1 & subrange1_y<=par_civ.ImageHeight;
586    check2_x=subrange2_x>=1 & subrange2_x<=par_civ.ImageWidth;% check which points in the subimage 2 are contained in the initial image 2
587    check2_y=subrange2_y>=1 & subrange2_y<=par_civ.ImageHeight;
588   
589    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
590    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
591    image1_mean=mean(mean(image1_crop));
592    image2_mean=mean(mean(image2_crop));
593    %threshold on image minimum
594    if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
595        F(ivec)=3;
596    end
597    %threshold on image maximum
598    if check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
599        F(ivec)=3;
600    end
601    %         end
602    if F(ivec)~=3
603        image1_crop=image1_crop-image1_mean;%substract the mean
604        image2_crop=image2_crop-image2_mean;
605        if CheckDecimal
606            xi=(1:mesh:size(image1_crop,2));
607            yi=(1:mesh:size(image1_crop,1))';
608            if CheckDeformation
609                [XI,YI]=meshgrid(xi-ceil(size(image1_crop,2)/2),yi-ceil(size(image1_crop,1)/2));
610                XIant=XI-par_civ.DUDX(ivec)*XI-par_civ.DUDY(ivec)*YI+ceil(size(image1_crop,2)/2);
611                YIant=YI-par_civ.DVDX(ivec)*XI-par_civ.DVDY(ivec)*YI+ceil(size(image1_crop,1)/2);
612                image1_crop=interp2(image1_crop,XIant,YIant);
613            else
614                image1_crop=interp2(image1_crop,xi,yi);
615            end
616            xi=(1:mesh:size(image2_crop,2));
617            yi=(1:mesh:size(image2_crop,1))';
618            image2_crop=interp2(image2_crop,xi,yi);
619        end
620        sum_square=sum(sum(image1_crop.*image1_crop));
621        %reference: Oliver Pust, PIV: Direct Cross-Correlation
622        result_conv= conv2(image2_crop,flipdim(flipdim(image1_crop,2),1),'valid');
623        corrmax= max(max(result_conv));
624        result_conv=(result_conv/corrmax)*255; %normalize, peak=always 255
625        %Find the correlation max, at 255
626        [y,x] = find(result_conv==255,1);
627        if ~isempty(y) && ~isempty(x)
628            try
629                if par_civ.CorrSmooth==1
630                    [vector,F(ivec)] = SUBPIXGAUSS (result_conv,x,y);
631                elseif par_civ.CorrSmooth==2
632                    [vector,F(ivec)] = SUBPIX2DGAUSS (result_conv,x,y);
633                end
634                utable(ivec)=vector(1)*mesh+shiftx(ivec);
635                vtable(ivec)=vector(2)*mesh+shifty(ivec);
636                xtable(ivec)=iref+utable(ivec)/2-0.5;% convec flow (velocity taken at the point middle from imgae 1 and 2)
637                ytable(ivec)=jref+vtable(ivec)/2-0.5;% and position of pixel 1=0.5 (convention for image coordinates=0 at the edge)
638                iref=round(xtable(ivec));% image index for the middle of the vector
639                jref=round(ytable(ivec));
640                if checkmask && par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100
641                    utable(ivec)=0;
642                    vtable(ivec)=0;
643                    F(ivec)=3;
644                end
645                ctable(ivec)=corrmax/sum_square;% correlation value
646            catch ME
647                F(ivec)=3;
648            end
649        else
650            F(ivec)=3;
651        end
652    end
653end
654result_conv=result_conv*corrmax/(255*sum_square);% keep the last correlation matrix for output
655
656%------------------------------------------------------------------------
657% --- Find the maximum of the correlation function after interpolation
658function [vector,F] = SUBPIXGAUSS (result_conv,x,y)
659%------------------------------------------------------------------------
660vector=[0 0]; %default
661F=0;
662[npy,npx]=size(result_conv);
663
664% if (x <= (size(result_conv,1)-1)) && (y <= (size(result_conv,1)-1)) && (x >= 1) && (y >= 1)
665    %the following 8 lines are copyright (c) 1998, Uri Shavit, Roi Gurka, Alex Liberzon, Technion ï¿œ Israel Institute of Technology
666    %http://urapiv.wordpress.com
667    peaky = y;
668    if y <= npy-1 && y >= 1
669        f0 = log(result_conv(y,x));
670        f1 = real(log(result_conv(y-1,x)));
671        f2 = real(log(result_conv(y+1,x)));
672        peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
673    else
674        F=-2; % warning flag for vector truncated by the limited search box
675    end
676    peakx=x;
677    if x <= npx-1 && x >= 1
678        f0 = log(result_conv(y,x));
679        f1 = real(log(result_conv(y,x-1)));
680        f2 = real(log(result_conv(y,x+1)));
681        peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
682    else
683        F=-2; % warning flag for vector truncated by the limited search box
684    end
685    vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
686
687%------------------------------------------------------------------------
688% --- Find the maximum of the correlation function after interpolation
689function [vector,F] = SUBPIX2DGAUSS (result_conv,x,y)
690%------------------------------------------------------------------------
691vector=[0 0]; %default
692F=-2;
693peaky=y;
694peakx=x;
695[npy,npx]=size(result_conv);
696if (x <= npx-1) && (y <= npy-1) && (x >= 1) && (y >= 1)
697    F=0;
698    for i=-1:1
699        for j=-1:1
700            %following 15 lines based on
701            %H. Nobach ï¿œ M. Honkanen (2005)
702            %Two-dimensional Gaussian regression for sub-pixel displacement
703            %estimation in particle image velocimetry or particle position
704            %estimation in particle tracking velocimetry
705            %Experiments in Fluids (2005) 38: 511ï¿œ515
706            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
707            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
708            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
709            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
710            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
711        end
712    end
713    c10=(1/6)*sum(sum(c10));
714    c01=(1/6)*sum(sum(c01));
715    c11=(1/4)*sum(sum(c11));
716    c20=(1/6)*sum(sum(c20));
717    c02=(1/6)*sum(sum(c02));
718    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11^2);
719    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11^2);
720    if abs(deltax)<1
721        peakx=x+deltax;
722    end
723    if abs(deltay)<1
724        peaky=y+deltay;
725    end
726end
727vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
728
729%'RUN_FIX': function for fixing velocity fields:
730%-----------------------------------------------
731% RUN_FIX(filename,field,flagindex,thresh_vecC,thresh_vel,iter,flag_mask,maskname,fileref,fieldref)
732%
733%filename: name of the netcdf file (used as input and output)
734%field: structure specifying the names of the fields to fix (depending on civ1 or civ2)
735    %.vel_type='civ1' or 'civ2';
736    %.nb=name of the dimension common to the field to fix ('nb_vectors' for civ1);
737    %.fixflag=name of fix flag variable ('vec_FixFlag' for civ1)
738%flagindex: flag specifying which values of vec_f are removed:
739        % if flagindex(1)=1: vec_f=-2 vectors are removed
740        % if flagindex(2)=1: vec_f=3 vectors are removed
741        % if flagindex(3)=1: vec_f=2 vectors are removed (if iter=1) or vec_f=4 vectors are removed (if iter=2)
742%iter=1 for civ1 fields and iter=2 for civ2 fields
743%thresh_vecC: threshold in the image correlation vec_C
744%flag_mask: =1 mask used to remove vectors (0 else)
745%maskname: name of the mask image file for fix
746%thresh_vel: threshold on velocity, or on the difference with the reference file fileref if exists
747%inf_sup=1: remove values smaller than threshold thresh_vel, =2, larger than threshold
748%fileref: .nc file name for a reference velocity (='': refrence 0 used)
749%fieldref: 'civ1','filter1'...feld used in fileref
750
751function FF=fix(Param,F,C,U,V,X,Y)
752FF=zeros(size(F));%default
753
754%criterium on warn flags
755FlagName={'CheckFmin2','CheckF2','CheckF3','CheckF4'};
756FlagVal=[-2 2 3 4];
757for iflag=1:numel(FlagName)
758    if isfield(Param,FlagName{iflag}) && Param.(FlagName{iflag})
759        FF=(FF==1| F==FlagVal(iflag));
760    end
761end
762%criterium on correlation values
763if isfield (Param,'MinCorr')
764    FF=FF==1 | C<Param.MinCorr;
765end
766if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
767    Umod= U.*U+V.*V;
768    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
769        FF=FF==1 | Umod<(Param.MinVel*Param.MinVel);
770    end
771    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
772        FF=FF==1 | Umod>(Param.MaxVel*Param.MaxVel);
773    end
774end
775
776
777
778
779
780
781
Note: See TracBrowser for help on using the repository browser.