source: trunk/src/civ_matlab.m @ 368

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

various bugs fixed

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