source: trunk/src/civ_matlab.m @ 363

Last change on this file since 363 was 363, checked in by sommeria, 12 years ago

civ2 introduced in civ_matlab (still bugs)
bugs corrected in civ and fill_GUI, read_GUI
comments in get_field

File size: 34.4 KB
Line 
1%'civ_matlab': Matlab version of the PIV programs CivX
2% --- call the sub-functions:
3%   civ: PIV function itself
4%   fix: removes false vectors after detection by various criteria
5%   patch: make interpolation-smoothing
6%------------------------------------------------------------------------
7% function [Data,errormsg,result_conv]= civ_uvmat(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% ncfile: name of a netcdf file to be created for the result (extension .nc)
17%
18%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
19%  Copyright  2011, LEGI / CNRS-UJF-INPG, joel.sommeria@legi.grenoble-inp.fr.
20%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
21%     This is part of the toolbox UVMAT.
22%
23%     UVMAT is free software; you can redistribute it and/or modify
24%     it under the terms of the GNU General Public License as published by
25%     the Free Software Foundation; either version 2 of the License, or
26%     (at your option) any later version.
27%
28%     UVMAT is distributed in the hope that it will be useful,
29%     but WITHOUT ANY WARRANTY; without even the implied warranty of
30%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
31%     GNU General Public License (open UVMAT/COPYING.txt) for more details.
32%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
33
34function [Data,errormsg,result_conv]= civ_matlab(Param,ncfile)
35errormsg='';
36Data.ListGlobalAttribute={'Conventions','Program','CivStage'};
37Data.Conventions='uvmat/civdata';% states the conventions used for the description of field variables and attributes
38Data.Program='civ_matlab';
39Data.CivStage=0;%default
40ListVarCiv1={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F'}; %variables to read
41ListVarFix1={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F','Civ1_FF'};
42mask='';
43maskname='';%default
44check_civx=0;%default
45check_civ1=0;%default
46check_patch1=0;%default
47
48if ischar(Param)
49    Param=xml2struct(Param);
50end
51
52%% Civ1
53if isfield (Param,'Civ1')
54    check_civ1=1;% test for further use of civ1 results
55    % caluclate velocity data (y and v in indices, reverse to y component)
56    [xtable ytable utable vtable ctable F result_conv errormsg] = civ (Param.Civ1);
57
58   % to try the reverse_pair method, uncomment below
59%     [xtable1 ytable1 utable1 vtable1 ctable1 F1 result_conv1 errormsg1] = civ (Param.Civ1);
60%     Param.Civ1.reverse_pair=1;
61%     [xtable2 ytable2 utable2 vtable2 ctable2 F2 result_conv2 errormsg2] = civ (Param.Civ1);
62%     xtable=[xtable1; xtable2];
63%     ytable=[ytable1; ytable2];
64%     utable=[utable1; -utable2];
65%     vtable=[vtable1; -vtable2];
66%     ctable=[ctable1; ctable2];
67%     F=[F1; F2];
68%     result_conv=[result_conv1; result_conv2];
69%     errormsg=[errormsg1; errormsg2];
70   
71   
72    if ~isempty(errormsg)
73        return
74    end
75    list_param=(fieldnames(Param.Civ1))';
76    Civ1_param=list_param;%default
77    for ilist=1:length(list_param)
78        Civ1_param{ilist}=['Civ1_' list_param{ilist}];
79        Data.(['Civ1_' list_param{ilist}])=Param.Civ1.(list_param{ilist});
80    end
81    Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ1_param];% {'Civ1_Time','Civ1_Dt'}];
82    Data.ListVarName={'Civ1_X','Civ1_Y','Civ1_U','Civ1_V','Civ1_C','Civ1_F'};%  cell array containing the names of the fields to record
83    Data.VarDimName={'NbVec1','NbVec1','NbVec1','NbVec1','NbVec1','NbVec1'};
84    Data.VarAttribute{1}.Role='coord_x';
85    Data.VarAttribute{2}.Role='coord_y';
86    Data.VarAttribute{3}.Role='vector_x';
87    Data.VarAttribute{4}.Role='vector_y';
88    Data.VarAttribute{5}.Role='warnflag';
89    Data.Civ1_X=reshape(xtable,[],1);
90    Data.Civ1_Y=reshape(Param.Civ1.ImageHeight-ytable+1,[],1);
91    Data.Civ1_U=reshape(utable,[],1);
92    Data.Civ1_V=reshape(-vtable,[],1);
93    Data.Civ1_C=reshape(ctable,[],1);
94    Data.Civ1_F=reshape(F,[],1);
95    Data.CivStage=1;
96   
97else
98    if exist('ncfile','var')
99        CivFile=ncfile;
100    elseif isfield(Param.Patch1,'CivFile')
101        CivFile=Param.Patch1.CivFile;
102    end
103    Data=nc2struct(CivFile,'ListGlobalAttribute','absolut_time_T0'); %look for the constant 'absolut_time_T0' to detect old civx data format
104    if isfield(Data,'Txt')
105        errormsg=Data.Txt;
106        return
107    end
108    if ~isempty(Data.absolut_time_T0')%read civx file
109        check_civx=1;% test for old civx data format
110        [Data,vardetect,ichoice]=nc2struct(CivFile);%read the variables in the netcdf file
111    else
112        Data=nc2struct(CivFile);%read civ1 and fix1 data in the existing netcdf file
113%         if isfield(Param,'Fix1')
114%             Data=nc2struct(CivFile,ListVarCiv1);%read civ1 data in the existing netcdf file
115%         else
116%             Data=nc2struct(CivFile,ListVarFix1);%read civ1 and fix1 data in the existing netcdf file
117%         end
118    end
119end
120
121%% Fix1
122if isfield (Param,'Fix1')
123    ListFixParam=fieldnames(Param.Fix1);
124    for ilist=1:length(ListFixParam)
125        ParamName=ListFixParam{ilist};
126        ListName=['Fix1_' ParamName];
127        eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
128        eval(['Data.' ListName '=Param.Fix1.' ParamName ';'])
129    end
130    if check_civx
131        if ~isfield(Data,'fix')
132            Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix'];
133            Data.fix=1;
134            Data.ListVarName=[Data.ListVarName {'vec_FixFlag'}];
135            Data.VarDimName=[Data.VarDimName {'nb_vectors'}];
136        end
137        Data.vec_FixFlag=fix(Param.Fix1,Data.vec_F,Data.vec_C,Data.vec_U,Data.vec_V,Data.vec_X,Data.vec_Y);
138    else
139        Data.ListVarName=[Data.ListVarName {'Civ1_FF'}];
140        Data.VarDimName=[Data.VarDimName {'NbVec1'}];
141        nbvar=length(Data.ListVarName);
142        Data.VarAttribute{nbvar}.Role='errorflag';   
143        Data.Civ1_FF=fix(Param.Fix1,Data.Civ1_F,Data.Civ1_C,Data.Civ1_U,Data.Civ1_V);
144        Data.CivStage=2;   
145    end
146end   
147%% Patch1
148if isfield (Param,'Patch1')
149    if check_civx
150        errormsg='Civ Matlab input needed for patch';
151        return
152    end
153    check_patch1=1;
154    Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch1_Rho','Patch1_Threshold','Patch1_SubDomain'}];
155    Data.Patch1_Rho=Param.Patch1.SmoothingParam;
156    Data.Patch1_Threshold=Param.Patch1.MaxDiff;
157    Data.Patch1_SubDomain=Param.Patch1.SubdomainSize;
158    Data.ListVarName=[Data.ListVarName {'Civ1_U_Diff','Civ1_V_Diff','Civ1_X_SubRange','Civ1_Y_SubRange','Civ1_NbSites','Civ1_X_tps','Civ1_Y_tps','Civ1_U_tps','Civ1_V_tps'}];
159    Data.VarDimName=[Data.VarDimName {'NbVec1','NbVec1',{'NbSubDomain1','Two'},{'NbSubDomain1','Two'},'NbSubDomain1',...
160             {'NbVec1Sub','NbSubDomain1'},{'NbVec1Sub','NbSubDomain1'},{'Nbtps1','NbSubDomain1'},{'Nbtps1','NbSubDomain1'}}];
161    nbvar=length(Data.ListVarName);
162    Data.VarAttribute{nbvar-1}.Role='vector_x';
163    Data.VarAttribute{nbvar}.Role='vector_y';
164    Data.Civ1_U_Diff=zeros(size(Data.Civ1_X));
165    Data.Civ1_V_Diff=zeros(size(Data.Civ1_X));
166    if isfield(Data,'Civ1_FF')
167        ind_good=find(Data.Civ1_FF==0);
168    else
169        ind_good=1:numel(Data.Civ1_X);
170    end
171    [Data.Civ1_X_SubRange,Data.Civ1_Y_SubRange,Data.Civ1_NbSites,FFres,Ures, Vres,Data.Civ1_X_tps,Data.Civ1_Y_tps,Data.Civ1_U_tps,Data.Civ1_V_tps]=...
172                            patch(Data.Civ1_X(ind_good)',Data.Civ1_Y(ind_good)',Data.Civ1_U(ind_good)',Data.Civ1_V(ind_good)',Data.Patch1_Rho,Data.Patch1_Threshold,Data.Patch1_SubDomain);
173      Data.Civ1_U_Diff(ind_good)=Data.Civ1_U(ind_good)-Ures;
174      Data.Civ1_V_Diff(ind_good)=Data.Civ1_V(ind_good)-Vres;
175      Data.Civ1_FF(ind_good)=FFres;
176      Data.CivStage=3;                             
177end   
178
179%% Civ2
180if isfield (Param,'Civ2')
181    par_civ2=Param.Civ2;
182    if ~isfield (Param,'Civ1') || ~strcmp(Param.Civ1.ImageA,par_civ2.ImageA)
183        par_civ2.ImageA=imread(par_civ2.ImageA);%read first image if not already done for civ1
184    else
185        par_civ2.ImageA=Param.Civ1.ImageA;
186    end
187    if ~isfield (Param,'Civ1') || ~strcmp(Param.Civ1.ImageB,par_civ2.ImageB)
188        par_civ2.ImageB=imread(par_civ2.ImageB);%read second image if not already done for civ1
189         else
190        par_civ2.ImageB=Param.Civ1.ImageB;
191    end
192    ibx2=ceil(par_civ2.Bx/2);
193    iby2=ceil(par_civ2.By/2);
194    isx2=ibx2+2;
195    isy2=iby2+2;
196    % shift from par_civ2.filename_nc1
197    % shiftx=velocity interpolated at position
198    miniy=max(1+isy2,1+iby2);
199    minix=max(1+isx2,1+ibx2);
200    maxiy=min(size(par_civ2.ImageA,1)-isy2,size(par_civ2.ImageA,1)-iby2);
201    maxix=min(size(par_civ2.ImageA,2)-isx2,size(par_civ2.ImageA,2)-ibx2);
202    [GridX,GridY]=meshgrid(minix:par_civ2.Dx:maxix,miniy:par_civ2.Dy:maxiy);
203    GridX=reshape(GridX,[],1);
204    GridY=reshape(GridY,[],1);
205    Shiftx=zeros(size(GridX));% shift expected from civ1 data
206    Shifty=zeros(size(GridX));
207    nbval=zeros(size(GridX));
208    if par_civ2.CheckDeformation
209        DUDX=zeros(size(GridX));
210        DUDY=zeros(size(GridX));
211        DVDX=zeros(size(GridX));
212        DVDY=zeros(size(GridX));
213    end
214    [NbSubDomain,xx]=size(Data.Civ1_X_SubRange);
215    % get the guess from patch1
216    for isub=1:NbSubDomain
217        nbvec_sub=Data.Civ1_NbSites(isub);
218        ind_sel=find(GridX>=Data.Civ1_X_SubRange(isub,1) & GridX<=Data.Civ1_X_SubRange(isub,2) & GridY>=Data.Civ1_Y_SubRange(isub,1) & GridY<=Data.Civ1_Y_SubRange(isub,2));
219        epoints = [GridX(ind_sel) GridY(ind_sel)];% coordinates of interpolation sites
220        ctrs=[Data.Civ1_X_tps(1:nbvec_sub,isub) Data.Civ1_Y_tps(1:nbvec_sub,isub)];%(=initial points) ctrs
221        nbval(ind_sel)=nbval(ind_sel)+1;% records the number of values for eacn interpolation point (in case of subdomain overlap)
222        EM = tps_eval(epoints,ctrs);
223        Shiftx(ind_sel)=Shiftx(ind_sel)+EM*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
224        Shifty(ind_sel)=Shifty(ind_sel)+EM*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
225        if par_civ2.CheckDeformation
226            [EMDX,EMDY] = tps_eval_dxy(epoints,ctrs);%2D matrix of distances between extrapolation points epoints and spline centres (=site points) ctrs
227            DUDX(ind_sel)=DUDX(ind_sel)+EMDX*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
228            DUDY(ind_sel)=DUDY(ind_sel)+EMDY*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
229            DVDX(ind_sel)=DVDX(ind_sel)+EMDX*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
230            DVDY(ind_sel)=DVDY(ind_sel)+EMDY*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
231        end
232    end
233    mask='';
234    if par_civ2.CheckMask&&~isempty(par_civ2.maskname)&& ~strcmp(maskname,par_civ2.maskname)% mask exist, not already read in civ1
235        mask=imread(par_civ2.maskname);
236    end
237    par_civ2.Searchx=2*isx2+1;
238    par_civ2.Searchy=2*isy2+1;
239    par_civ2.Shiftx=Shiftx./nbval;
240    par_civ2.Shifty=Shifty./nbval;
241    par_civ2.Grid=[GridX GridY];   
242    if par_civ2.CheckDeformation
243        DUDX=DUDX./nbval;
244        DUDY=DUDY./nbval;
245        DVDX=DVDX./nbval;
246        DVDY=DVDY./nbval;
247    end
248    % caluclate velocity data (y and v in indices, reverse to y component)
249    [xtable ytable utable vtable ctable F] = civ (par_civ2);
250    list_param=(fieldnames(Param.Civ2))';
251    list_remove={'pxcmx','pxcmy','npx','npy','gridflag','maskflag','term_a','term_b','T0'};
252    for ilist=1:length(list_remove)
253        index=strcmp(list_remove{ilist},list_param);
254        if ~isempty(find(index,1))
255            list_param(index)=[];
256        end
257    end
258    for ilist=1:length(list_param)
259        Civ2_param{ilist}=['Civ2_' list_param{ilist}];
260        eval(['Data.Civ2_' list_param{ilist} '=Param.Civ2.' list_param{ilist} ';'])
261    end
262    if isfield(Data,'Civ2_gridname') && strcmp(Data.Civ1_gridname(1:6),'noFile')
263        Data.Civ1_gridname='';
264    end
265    if isfield(Data,'Civ2_maskname') && strcmp(Data.Civ1_maskname(1:6),'noFile')
266        Data.Civ2_maskname='';
267    end
268    Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ2_param {'Civ2_Time','Civ2_Dt'}];
269    Data.Civ2_Time=str2double(par_civ2.Time);
270    Data.Civ2_Dt=str2double(par_civ2.Dt);
271    Data.ListVarName=[Data.ListVarName {'Civ2_X','Civ2_Y','Civ2_U','Civ2_V','Civ2_C','Civ2_F'}];%  cell array containing the names of the fields to record
272    Data.VarDimName=[Data.VarDimName {'NbVec2','NbVec2','NbVec2','NbVec2','NbVec2','NbVec2'}];
273    Data.VarAttribute{1}.Role='coord_x';
274    Data.VarAttribute{2}.Role='coord_y';
275    Data.VarAttribute{3}.Role='vector_x';
276    Data.VarAttribute{4}.Role='vector_y';
277    Data.VarAttribute{5}.Role='warnflag';
278    Data.Civ2_X=reshape(xtable,[],1);
279    Data.Civ2_Y=reshape(size(par_civ2.ImageA,1)-ytable+1,[],1);
280    Data.Civ2_U=reshape(utable,[],1);
281    Data.Civ2_V=reshape(-vtable,[],1);
282    Data.Civ2_C=reshape(ctable,[],1);
283    Data.Civ2_F=reshape(F,[],1);
284    Data.CivStage=Data.CivStage+1;
285end
286
287%% Fix2
288if isfield (Param,'Fix2')
289    ListFixParam=fieldnames(Param.Fix2);
290    for ilist=1:length(ListFixParam)
291        ParamName=ListFixParam{ilist};
292        ListName=['Fix1_' ParamName];
293        eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
294        eval(['Data.' ListName '=Param.Fix2.' ParamName ';'])
295    end
296    if check_civx
297        if ~isfield(Data,'fix2')
298            Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix2'];
299            Data.fix2=1;
300            Data.ListVarName=[Data.ListVarName {'vec2_FixFlag'}];
301            Data.VarDimName=[Data.VarDimName {'nb_vectors2'}];
302        end
303        Data.vec_FixFlag=fix(Param.Fix2,Data.vec2_F,Data.vec2_C,Data.vec2_U,Data.vec2_V,Data.vec2_X,Data.vec2_Y);
304    else
305        Data.ListVarName=[Data.ListVarName {'Civ2_FF'}];
306        Data.VarDimName=[Data.VarDimName {'nbvec2'}];
307        nbvar=length(Data.ListVarName);
308        Data.VarAttribute{nbvar}.Role='errorflag';   
309        Data.Civ2_FF=fix(Param.Fix2,Data.Civ2_F,Data.Civ2_C,Data.Civ2_U,Data.Civ2_V);
310        Data.CivStage=5;   
311    end
312   
313end   
314
315%% Patch2
316if isfield (Param,'Patch2')
317    Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch2_Rho','Patch2_Threshold','Patch2_SubDomain'}];
318    Data.Patch2_Rho=str2double(Param.Patch2.Rho);
319    Data.Patch2_Threshold=str2double(Param.Patch2.Threshold);
320    Data.Patch2_SubDomain=str2double(Param.Patch2.SubDomain);
321    Data.ListVarName=[Data.ListVarName {'Civ2_U_Diff','Civ2_V_Diff','Civ2_X_SubRange','Civ2_Y_SubRange','Civ2_NbSites','Civ2_X_tps','Civ2_Y_tps','Civ2_U_tps','Civ2_V_tps'}];
322    Data.VarDimName=[Data.VarDimName {'NbVec2','NbVec2',{'NbSubDomain2','Two'},{'NbSubDomain2','Two'},'NbSubDomain2',...
323             {'NbVec2Sub','NbSubDomain2'},{'NbVec2Sub','NbSubDomain2'},{'Nbtps2','NbSubDomain2'},{'Nbtps2','NbSubDomain2'}}];
324    nbvar=length(Data.ListVarName);
325    Data.VarAttribute{nbvar-1}.Role='vector_x';
326    Data.VarAttribute{nbvar}.Role='vector_y';
327    Data.Civ2_U_Diff=zeros(size(Data.Civ2_X));
328    Data.Civ2_V_Diff=zeros(size(Data.Civ2_X));
329    if isfield(Data,'Civ2_FF')
330        ind_good=find(Data.Civ2_FF==0);
331    else
332        ind_good=1:numel(Data.Civ2_X);
333    end
334    [Data.Civ2_X_SubRange,Data.Civ2_Y_SubRange,Data.Civ2_NbSites,FFres,Ures, Vres,Data.Civ2_X_tps,Data.Civ2_Y_tps,Data.Civ2_U_tps,Data.Civ2_V_tps]=...
335                            patch(Data.Civ2_X(ind_good)',Data.Civ2_Y(ind_good)',Data.Civ2_U(ind_good)',Data.Civ2_V(ind_good)',Data.Patch2_Rho,Data.Patch2_Threshold,Data.Patch2_SubDomain);
336      Data.Civ2_U_Diff(ind_good)=Data.Civ2_U(ind_good)-Ures;
337      Data.Civ2_V_Diff(ind_good)=Data.Civ2_V(ind_good)-Vres;
338      Data.Civ2_FF(ind_good)=FFres;
339      Data.CivStage=6;                             
340end   
341
342%% write result in a netcdf file if requested
343if exist('ncfile','var')
344    errormsg=struct2nc(ncfile,Data);
345end
346
347% 'civ': function piv.m adapted from PIVlab http://pivlab.blogspot.com/
348%--------------------------------------------------------------------------
349% function [xtable ytable utable vtable typevector] = civ (image1,image2,ibx,iby step, subpixfinder, mask, roi)
350%
351% OUTPUT:
352% xtable: set of x coordinates
353% ytable: set of y coordiantes
354% utable: set of u displacements (along x)
355% vtable: set of v displacements (along y)
356% ctable: max image correlation for each vector
357% typevector: set of flags, =1 for good, =0 for NaN vectors
358%
359%INPUT:
360% image1:first image (matrix)
361% image2: second image (matrix)
362% ibx2,iby2: half size of the correlation box along x and y, in px (size=(2*iby2+1,2*ibx2+1)
363% isx2,isy2: half size of the search box along x and y, in px (size=(2*isy2+1,2*isx2+1)
364% shiftx, shifty: shift of the search box (in pixel index, yshift reversed)
365% step: mesh of the measurement points (in px)
366% subpixfinder=1 or 2 controls the curve fitting of the image correlation
367% mask: =[] for no mask
368% roi: 4 element vector defining a region of interest: x position, y position, width, height, (in image indices), for the whole image, roi=[];
369function [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ)
370%this funtion performs the DCC PIV analysis. Recent window-deformation
371%methods perform better and will maybe be implemented in the future.
372
373%% prepare grid
374ibx2=ceil(par_civ.Bx/2);
375iby2=ceil(par_civ.By/2);
376isx2=ceil(par_civ.Searchx/2);
377isy2=ceil(par_civ.Searchy/2);
378shiftx=par_civ.Shiftx;
379shifty=-par_civ.Shifty;% sign minus because image j index increases when y decreases
380if isfield(par_civ,'Grid')
381    if ischar(par_civ.Grid)
382        par_civ.Grid=dlmread(par_civ.Grid);
383        par_civ.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
384    end
385else% automatic measurement grid
386    ibx2=ceil(par_civ.Bx/2);
387    iby2=ceil(par_civ.By/2);
388    isx2=ceil(par_civ.Searchx/2);
389    isy2=ceil(par_civ.Searchy/2);
390    miniy=max(1+isy2+shifty,1+iby2);
391    minix=max(1+isx2-shiftx,1+ibx2);
392    maxiy=min(par_civ.ImageHeight-isy2+shifty,par_civ.ImageHeight-iby2);
393    maxix=min(par_civ.ImageWidth-isx2-shiftx,par_civ.ImageWidth-ibx2);
394    [GridX,GridY]=meshgrid(minix:par_civ.Dx:maxix,miniy:par_civ.Dy:maxiy);
395    par_civ.Grid(:,1)=reshape(GridX,[],1);
396    par_civ.Grid(:,2)=reshape(GridY,[],1);
397end
398nbvec=size(par_civ.Grid,1);
399if numel(shiftx)==1
400    shiftx=round(shiftx)*ones(nbvec,1);
401    shifty=round(shifty)*ones(nbvec,1);
402end
403%% Default output
404xtable=par_civ.Grid(:,1);
405ytable=par_civ.Grid(:,2);
406utable=zeros(nbvec,1);
407vtable=zeros(nbvec,1);
408ctable=zeros(nbvec,1);
409F=zeros(nbvec,1);
410result_conv=[];
411errormsg='';
412
413%% prepare mask
414if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
415    if strcmp(par_civ.Mask,'all')
416        return    % get the grid only, no civ calculation
417    elseif ischar(par_civ.Mask)
418        par_civ.Mask=imread(par_civ.Mask);
419    end
420end
421check_MinIma=isfield(par_civ,'MinIma');% test for image luminosity threshold
422check_MaxIma=isfield(par_civ,'MaxIma') && ~isempty(par_civ.MaxIma);
423
424%% prepare images
425if isfield(par_civ,'reverse_pair')
426    if par_civ.reverse_pair
427        if ischar(par_civ.ImageB)
428            temp=par_civ.ImageA;
429            par_civ.ImageA=imread(par_civ.ImageB);
430        end
431        if ischar(temp)
432            par_civ.ImageB=imread(temp);
433        end
434    end
435else
436    if ischar(par_civ.ImageA)
437        par_civ.ImageA=imread(par_civ.ImageA);
438    end
439    if ischar(par_civ.ImageB)
440        par_civ.ImageB=imread(par_civ.ImageB);
441    end
442end
443
444[npy_ima npx_ima]=size(par_civ.ImageA);
445if ~isequal(size(par_civ.ImageB),[npy_ima npx_ima])
446    errormsg='image pair with unequal size';
447    return
448end
449par_civ.ImageA=double(par_civ.ImageA);
450par_civ.ImageB=double(par_civ.ImageB);
451
452
453%% Apply mask
454    % Convention for mask
455    % mask >200 : velocity calculated
456    %  200 >=mask>150;velocity not calculated, interpolation allowed (bad spots)
457    % 150>=mask >100: velocity not calculated, nor interpolated
458    %  100>=mask> 20: velocity not calculated, impermeable (no flux through mask boundaries) TO IMPLEMENT
459    %  20>=mask: velocity=0
460checkmask=0;
461if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
462   checkmask=1;
463   if ~isequal(size(par_civ.Mask),[npy_ima npx_ima])
464        errormsg='mask must be an image with the same size as the images';
465        return
466   end
467  %  check_noflux=(par_civ.Mask<100) ;%TODO: to implement
468    check_undefined=(par_civ.Mask<200 & par_civ.Mask>=100 );
469    par_civ.ImageA(check_undefined)=min(min(par_civ.ImageA));% put image A to zero (i.e. the min image value) in the undefined  area
470    par_civ.ImageB(check_undefined)=min(min(par_civ.ImageB));% put image B to zero (i.e. the min image value) in the undefined  area
471end
472
473%% compute image correlations: MAINLOOP on velocity vectors
474corrmax=0;
475sum_square=1;% default
476% vector=[0 0];%default
477for ivec=1:nbvec
478    iref=par_civ.Grid(ivec,1);% xindex on the image A for the middle of the correlation box
479    jref=par_civ.Grid(ivec,2);% yindex on the image B for the middle of the correlation box
480    %     xtable(ivec)=iref;
481    %     ytable(ivec)=jref;%default
482    if ~(checkmask && par_civ.Mask(jref,iref)<=20) %velocity not set to zero by the black mask
483        if jref-iby2<1 || jref+iby2>par_civ.ImageHeight|| iref-ibx2<1 || iref+ibx2>par_civ.ImageWidth||...
484              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
485            F(ivec)=3;
486        else
487            image1_crop=par_civ.ImageA(jref-iby2:jref+iby2,iref-ibx2:iref+ibx2);%extract a subimage (correlation box) from image A
488            image2_crop=par_civ.ImageB(jref+shifty(ivec)-isy2:jref+shifty(ivec)+isy2,iref+shiftx(ivec)-isx2:iref+shiftx(ivec)+isx2);%extract a larger subimage (search box) from image B
489            image1_mean=mean(mean(image1_crop));
490            image2_mean=mean(mean(image2_crop));
491            %threshold on image minimum
492            if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
493                F(ivec)=3;
494            end
495            %threshold on image maximum
496            if check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
497                F(ivec)=3;
498            end
499        end
500       
501        if F(ivec)~=3
502            image1_crop=image1_crop-image1_mean;%substract the mean
503            image2_crop=image2_crop-image2_mean;
504            sum_square=sum(sum(image1_crop.*image1_crop));
505            %reference: Oliver Pust, PIV: Direct Cross-Correlation
506            result_conv= conv2(image2_crop,flipdim(flipdim(image1_crop,2),1),'valid');
507            corrmax= max(max(result_conv));
508            result_conv=(result_conv/corrmax)*255; %normalize, peak=always 255
509            %Find the correlation max, at 255
510            [y,x] = find(result_conv==255,1);
511            if ~isempty(y) && ~isempty(x)
512                try
513                    if par_civ.Rho==1
514                        [vector,F(ivec)] = SUBPIXGAUSS (result_conv,x,y);
515                    elseif par_civ.Rho==2
516                        [vector,F(ivec)] = SUBPIX2DGAUSS (result_conv,x,y);
517                    end
518                    utable(ivec)=vector(1)+shiftx(ivec);
519                    vtable(ivec)=vector(2)+shifty(ivec);
520                    xtable(ivec)=iref+utable(ivec)/2;% convec flow (velocity taken at the point middle from imgae1 and 2)
521                    ytable(ivec)=jref+vtable(ivec)/2;
522                    iref=round(xtable(ivec));% image index for the middle of the vector
523                    jref=round(ytable(ivec));
524                    if checkmask && par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100
525                        utable(ivec)=0;
526                        vtable(ivec)=0;
527                        F(ivec)=3;
528                    end
529                    ctable(ivec)=corrmax/sum_square;% correlation value
530                catch ME
531                    F(ivec)=3;
532                end
533            else
534                F(ivec)=3;
535            end
536        end
537    end
538   
539    %Create the vector matrix x, y, u, v
540end
541result_conv=result_conv*corrmax/(255*sum_square);% keep the last correlation matrix for output
542
543%------------------------------------------------------------------------
544% --- Find the maximum of the correlation function after interpolation
545function [vector,F] = SUBPIXGAUSS (result_conv,x,y)
546%------------------------------------------------------------------------
547vector=[0 0]; %default
548F=0;
549[npy,npx]=size(result_conv);
550
551% if (x <= (size(result_conv,1)-1)) && (y <= (size(result_conv,1)-1)) && (x >= 1) && (y >= 1)
552    %the following 8 lines are copyright (c) 1998, Uri Shavit, Roi Gurka, Alex Liberzon, Technion ï¿œ Israel Institute of Technology
553    %http://urapiv.wordpress.com
554    peaky = y;
555    if y <= npy-1 && y >= 1
556        f0 = log(result_conv(y,x));
557        f1 = real(log(result_conv(y-1,x)));
558        f2 = real(log(result_conv(y+1,x)));
559        peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
560    else
561        F=-2; % warning flag for vector truncated by the limited search box
562    end
563    peakx=x;
564    if x <= npx-1 && x >= 1
565        f0 = log(result_conv(y,x));
566        f1 = real(log(result_conv(y,x-1)));
567        f2 = real(log(result_conv(y,x+1)));
568        peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
569    else
570        F=-2; % warning flag for vector truncated by the limited search box
571    end
572    vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
573
574%------------------------------------------------------------------------
575% --- Find the maximum of the correlation function after interpolation
576function [vector,F] = SUBPIX2DGAUSS (result_conv,x,y)
577%------------------------------------------------------------------------
578vector=[0 0]; %default
579F=-2;
580peaky=y;
581peakx=x;
582[npy,npx]=size(result_conv);
583if (x <= npx-1) && (y <= npy-1) && (x >= 1) && (y >= 1)
584    F=0;
585    for i=-1:1
586        for j=-1:1
587            %following 15 lines based on
588            %H. Nobach ï¿œ M. Honkanen (2005)
589            %Two-dimensional Gaussian regression for sub-pixel displacement
590            %estimation in particle image velocimetry or particle position
591            %estimation in particle tracking velocimetry
592            %Experiments in Fluids (2005) 38: 511ï¿œ515
593            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
594            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
595            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
596            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
597            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
598        end
599    end
600    c10=(1/6)*sum(sum(c10));
601    c01=(1/6)*sum(sum(c01));
602    c11=(1/4)*sum(sum(c11));
603    c20=(1/6)*sum(sum(c20));
604    c02=(1/6)*sum(sum(c02));
605    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11^2);
606    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11^2);
607    if abs(deltax)<1
608        peakx=x+deltax;
609    end
610    if abs(deltay)<1
611        peaky=y+deltay;
612    end
613end
614vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
615
616%'RUN_FIX': function for fixing velocity fields:
617%-----------------------------------------------
618% RUN_FIX(filename,field,flagindex,thresh_vecC,thresh_vel,iter,flag_mask,maskname,fileref,fieldref)
619%
620%filename: name of the netcdf file (used as input and output)
621%field: structure specifying the names of the fields to fix (depending on civ1 or civ2)
622    %.vel_type='civ1' or 'civ2';
623    %.nb=name of the dimension common to the field to fix ('nb_vectors' for civ1);
624    %.fixflag=name of fix flag variable ('vec_FixFlag' for civ1)
625%flagindex: flag specifying which values of vec_f are removed:
626        % if flagindex(1)=1: vec_f=-2 vectors are removed
627        % if flagindex(2)=1: vec_f=3 vectors are removed
628        % if flagindex(3)=1: vec_f=2 vectors are removed (if iter=1) or vec_f=4 vectors are removed (if iter=2)
629%iter=1 for civ1 fields and iter=2 for civ2 fields
630%thresh_vecC: threshold in the image correlation vec_C
631%flag_mask: =1 mask used to remove vectors (0 else)
632%maskname: name of the mask image file for fix
633%thresh_vel: threshold on velocity, or on the difference with the reference file fileref if exists
634%inf_sup=1: remove values smaller than threshold thresh_vel, =2, larger than threshold
635%fileref: .nc file name for a reference velocity (='': refrence 0 used)
636%fieldref: 'civ1','filter1'...feld used in fileref
637
638function FF=fix(Param,F,C,U,V,X,Y)
639FF=zeros(size(F));%default
640
641%criterium on warn flags
642FlagName={'CheckFmin2','CheckF2','CheckF3','CheckF4'};
643FlagVal=[-2 2 3 4];
644for iflag=1:numel(FlagName)
645    if isfield(Param,FlagName{iflag}) && Param.(FlagName{iflag})
646        FF=(FF==1| F==FlagVal(iflag));
647    end
648end
649%criterium on correlation values
650if isfield (Param,'MinCorr')
651    FF=FF==1 | C<Param.MinCorr;
652end
653if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
654    Umod= U.*U+V.*V;
655    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
656        FF=FF==1 | Umod<(Param.MinVel*Param.MinVel);
657    end
658    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
659        FF=FF==1 | Umod>(Param.MaxVel*Param.MaxVel);
660    end
661end
662return
663
664
665FF=double(FF);
666
667
668
669%------------------------------------------------------------------------
670% patch function
671% OUTPUT:
672% SubRangx,SubRangy(NbSubdomain,2): range (min, max) of the coordiantes x and y respectively, for each subdomain
673% nbpoints(NbSubdomain): number of source points for each subdomain
674% FF: false flags
675% U_smooth, V_smooth: filtered velocity components at the positions of the initial data
676% X_tps,Y_tps,U_tps,V_tps: positions and weight of the tps for each subdomain
677%
678% INPUT:
679% X, Y: set of coordinates of the initial data
680% U,V: set of velocity components of the initial data
681% Rho: smoothing parameter
682% Threshold: max diff accepted between smoothed and initial data
683% Subdomain: estimated number of data points in each subdomain
684
685function [SubRangx,SubRangy,nbpoints,FF,U_smooth,V_smooth,X_tps,Y_tps,U_tps,V_tps] =patch(X,Y,U,V,Rho,Threshold,SubDomain)
686%subdomain decomposition
687warning off
688U=reshape(U,[],1);
689V=reshape(V,[],1);
690X=reshape(X,[],1);
691Y=reshape(Y,[],1);
692nbvec=numel(X);
693NbSubDomain=ceil(nbvec/SubDomain);
694MinX=min(X);
695MinY=min(Y);
696MaxX=max(X);
697MaxY=max(Y);
698RangX=MaxX-MinX;
699RangY=MaxY-MinY;
700AspectRatio=RangY/RangX;
701NbSubDomainX=max(floor(sqrt(NbSubDomain/AspectRatio)),1);
702NbSubDomainY=max(floor(sqrt(NbSubDomain*AspectRatio)),1);
703NbSubDomain=NbSubDomainX*NbSubDomainY;
704SizX=RangX/NbSubDomainX;%width of subdomains
705SizY=RangY/NbSubDomainY;%height of subdomains
706CentreX=linspace(MinX+SizX/2,MaxX-SizX/2,NbSubDomainX);
707CentreY=linspace(MinY+SizY/2,MaxY-SizY/2,NbSubDomainY);
708[CentreX,CentreY]=meshgrid(CentreX,CentreY);
709CentreY=reshape(CentreY,1,[]);% Y positions of subdomain centres
710CentreX=reshape(CentreX,1,[]);% X positions of subdomain centres
711rho=SizX*SizY*Rho/1000000;%optimum rho increase as the area of the subdomain (division by 10^6 to reach good values with the default GUI input)
712U_tps_sub=zeros(length(X),NbSubDomain);%default spline
713V_tps_sub=zeros(length(X),NbSubDomain);%default spline
714U_smooth=zeros(length(X),1);
715V_smooth=zeros(length(X),1);
716
717nb_select=zeros(length(X),1);
718FF=zeros(length(X),1);
719check_empty=zeros(1,NbSubDomain);
720SubRangx=zeros(NbSubDomain,2);%initialise the positions of subdomains
721SubRangy=zeros(NbSubDomain,2);
722for isub=1:NbSubDomain
723    SubRangx(isub,:)=[CentreX(isub)-0.55*SizX CentreX(isub)+0.55*SizX];
724    SubRangy(isub,:)=[CentreY(isub)-0.55*SizY CentreY(isub)+0.55*SizY];
725    ind_sel_previous=[];
726    ind_sel=0;
727    while numel(ind_sel)>numel(ind_sel_previous) %increase the subdomain during four iterations at most
728        ind_sel_previous=ind_sel;
729        ind_sel=find(X>=SubRangx(isub,1) & X<=SubRangx(isub,2) & Y>=SubRangy(isub,1) & Y<=SubRangy(isub,2));
730        % if no vector in the subdomain, skip the subdomain
731        if isempty(ind_sel)
732            check_empty(isub)=1;   
733            U_tps(1,isub)=0;%define U_tps and V_tps by default
734            V_tps(1,isub)=0;
735            break
736            % if too few selected vectors, increase the subrange for next iteration
737        elseif numel(ind_sel)<SubDomain/4 && ~isequal( ind_sel,ind_sel_previous);
738            SubRangx(isub,1)=SubRangx(isub,1)-SizX/4;
739            SubRangx(isub,2)=SubRangx(isub,2)+SizX/4;
740            SubRangy(isub,1)=SubRangy(isub,1)-SizY/4;
741            SubRangy(isub,2)=SubRangy(isub,2)+SizY/4;
742        else
743           
744            [U_smooth_sub,U_tps_sub]=tps_coeff([X(ind_sel) Y(ind_sel)],U(ind_sel),rho);
745            [V_smooth_sub,V_tps_sub]=tps_coeff([X(ind_sel) Y(ind_sel)],V(ind_sel),rho);
746            UDiff=U_smooth_sub-U(ind_sel);
747            VDiff=V_smooth_sub-V(ind_sel);
748            NormDiff=UDiff.*UDiff+VDiff.*VDiff;
749            FF(ind_sel)=20*(NormDiff>Threshold);%put FF value to 20 to identify the criterium of elimmination
750            ind_ind_sel=find(FF(ind_sel)==0); % select the indices of ind_sel corresponding to the remaining vectors
751            % no value exceeds threshold, the result is recorded
752            if isequal(numel(ind_ind_sel),numel(ind_sel))
753                U_smooth(ind_sel)=U_smooth(ind_sel)+U_smooth_sub;
754                V_smooth(ind_sel)=V_smooth(ind_sel)+V_smooth_sub;
755                nbpoints(isub)=numel(ind_sel);
756                X_tps(1:nbpoints(isub),isub)=X(ind_sel);
757                Y_tps(1:nbpoints(isub),isub)=Y(ind_sel);
758                U_tps(1:nbpoints(isub)+3,isub)=U_tps_sub;
759                V_tps(1:nbpoints(isub)+3,isub)=V_tps_sub;         
760                nb_select(ind_sel)=nb_select(ind_sel)+1;
761                 display('good')
762                break
763                % too few selected vectors, increase the subrange for next iteration
764            elseif numel(ind_ind_sel)<SubDomain/4 && ~isequal( ind_sel,ind_sel_previous);
765                SubRangx(isub,1)=SubRangx(isub,1)-SizX/4;
766                SubRangx(isub,2)=SubRangx(isub,2)+SizX/4;
767                SubRangy(isub,1)=SubRangy(isub,1)-SizY/4;
768                SubRangy(isub,2)=SubRangy(isub,2)+SizY/4;
769%                 display('fewsmooth')
770                % interpolation-smoothing is done again with the selected vectors
771            else
772                [U_smooth_sub,U_tps_sub]=tps_coeff([X(ind_sel(ind_ind_sel)) Y(ind_sel(ind_ind_sel))],U(ind_sel(ind_ind_sel)),rho);
773                [V_smooth_sub,V_tps_sub]=tps_coeff([X(ind_sel(ind_ind_sel)) Y(ind_sel(ind_ind_sel))],V(ind_sel(ind_ind_sel)),rho);
774                U_smooth(ind_sel(ind_ind_sel))=U_smooth(ind_sel(ind_ind_sel))+U_smooth_sub;
775                V_smooth(ind_sel(ind_ind_sel))=V_smooth(ind_sel(ind_ind_sel))+V_smooth_sub;
776                nbpoints(isub)=numel(ind_ind_sel);
777                X_tps(1:nbpoints(isub),isub)=X(ind_sel(ind_ind_sel));
778                Y_tps(1:nbpoints(isub),isub)=Y(ind_sel(ind_ind_sel));
779                U_tps(1:nbpoints(isub)+3,isub)=U_tps_sub;
780                V_tps(1:nbpoints(isub)+3,isub)=V_tps_sub;
781                nb_select(ind_sel(ind_ind_sel))=nb_select(ind_sel(ind_ind_sel))+1;
782                display('good2')
783                break
784            end
785        end
786    end
787end
788ind_empty=find(check_empty);
789%remove empty subdomains
790if ~isempty(ind_empty)
791    SubRangx(ind_empty,:)=[];
792    SubRangy(ind_empty,:)=[];
793    X_tps(:,ind_empty)=[];
794    Y_tps(:,ind_empty)=[];
795    U_tps(:,ind_empty)=[];
796    V_tps(:,ind_empty)=[];
797end
798nb_select(nb_select==0)=1;%ones(size(find(nb_select==0)));
799U_smooth=U_smooth./nb_select;
800V_smooth=V_smooth./nb_select;
801
802
803
804
805
Note: See TracBrowser for help on using the repository browser.