source: trunk/src/civ_matlab.m @ 372

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

many bugs repaired.

File size: 36.5 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        par_civ2.DUDX=DUDX./nbval;
257        par_civ2.DUDY=DUDY./nbval;
258        par_civ2.DVDX=DVDX./nbval;
259        par_civ2.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=par_civ2.Time;
285%     Data.Civ2_Dt=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
496    CheckDeformation=isfield(par_civ,'CheckDeformation')&& par_civ.CheckDeformation==1;
497end
498% vector=[0 0];%default
499for ivec=1:nbvec
500    iref=round(par_civ.Grid(ivec,1)+0.5);% xindex on the image A for the middle of the correlation box
501    jref=round(par_civ.ImageHeight-par_civ.Grid(ivec,2)+0.5);% yindex on the image B for the middle of the correlation box
502    if ~(checkmask && par_civ.Mask(jref,iref)<=20) %velocity not set to zero by the black mask
503        if jref-iby2<1 || jref+iby2>par_civ.ImageHeight|| iref-ibx2<1 || iref+ibx2>par_civ.ImageWidth||...
504              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
505            F(ivec)=3;
506        else
507            image1_crop=par_civ.ImageA(jref-iby2:jref+iby2,iref-ibx2:iref+ibx2);%extract a subimage (correlation box) from image A
508            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
509            image1_mean=mean(mean(image1_crop));
510            image2_mean=mean(mean(image2_crop));
511            %threshold on image minimum
512            if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
513                F(ivec)=3;
514            end
515            %threshold on image maximum
516            if check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
517                F(ivec)=3;
518            end
519        end     
520        if F(ivec)~=3
521            image1_crop=image1_crop-image1_mean;%substract the mean
522            image2_crop=image2_crop-image2_mean;
523            if CheckDecimal
524                xi=(1:mesh:size(image1_crop,2));
525                yi=(1:mesh:size(image1_crop,1))';
526                if CheckDeformation
527                    [XI,YI]=meshgrid(xi-ceil(size(image1_crop,2)/2),yi-ceil(size(image1_crop,1)/2));
528                    XIant=XI-par_civ.DUDX(ivec)*XI-par_civ.DUDY(ivec)*YI+ceil(size(image1_crop,2)/2);
529                    YIant=YI-par_civ.DVDX(ivec)*XI-par_civ.DVDY(ivec)*YI+ceil(size(image1_crop,1)/2);
530                    image1_crop=interp2(image1_crop,XIant,YIant);
531                else
532                    image1_crop=interp2(image1_crop,xi,yi);
533                end
534                xi=(1:mesh:size(image2_crop,2));
535                yi=(1:mesh:size(image2_crop,1))';
536                image2_crop=interp2(image2_crop,xi,yi);
537            end
538            sum_square=sum(sum(image1_crop.*image1_crop));
539            %reference: Oliver Pust, PIV: Direct Cross-Correlation
540            result_conv= conv2(image2_crop,flipdim(flipdim(image1_crop,2),1),'valid');
541            corrmax= max(max(result_conv));
542            result_conv=(result_conv/corrmax)*255; %normalize, peak=always 255
543            %Find the correlation max, at 255
544            [y,x] = find(result_conv==255,1);
545            if ~isempty(y) && ~isempty(x)
546                try
547                    if par_civ.Rho==1
548                        [vector,F(ivec)] = SUBPIXGAUSS (result_conv,x,y);
549                    elseif par_civ.Rho==2
550                        [vector,F(ivec)] = SUBPIX2DGAUSS (result_conv,x,y);
551                    end
552                    utable(ivec)=vector(1)*mesh+shiftx(ivec);
553                    vtable(ivec)=vector(2)*mesh+shifty(ivec);                 
554                    xtable(ivec)=iref+utable(ivec)/2-0.5;% convec flow (velocity taken at the point middle from imgae 1 and 2)
555                    ytable(ivec)=jref+vtable(ivec)/2-0.5;% and position of pixel 1=0.5 (convention for image coordinates=0 at the edge)
556                    iref=round(xtable(ivec));% image index for the middle of the vector
557                    jref=round(ytable(ivec));
558                    if checkmask && par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100
559                        utable(ivec)=0;
560                        vtable(ivec)=0;
561                        F(ivec)=3;
562                    end
563                    ctable(ivec)=corrmax/sum_square;% correlation value
564                catch ME
565                    F(ivec)=3;
566                end
567            else
568                F(ivec)=3;
569            end
570        end
571    end
572   
573    %Create the vector matrix x, y, u, v
574end
575result_conv=result_conv*corrmax/(255*sum_square);% keep the last correlation matrix for output
576
577%------------------------------------------------------------------------
578% --- Find the maximum of the correlation function after interpolation
579function [vector,F] = SUBPIXGAUSS (result_conv,x,y)
580%------------------------------------------------------------------------
581vector=[0 0]; %default
582F=0;
583[npy,npx]=size(result_conv);
584
585% if (x <= (size(result_conv,1)-1)) && (y <= (size(result_conv,1)-1)) && (x >= 1) && (y >= 1)
586    %the following 8 lines are copyright (c) 1998, Uri Shavit, Roi Gurka, Alex Liberzon, Technion ï¿œ Israel Institute of Technology
587    %http://urapiv.wordpress.com
588    peaky = y;
589    if y <= npy-1 && y >= 1
590        f0 = log(result_conv(y,x));
591        f1 = real(log(result_conv(y-1,x)));
592        f2 = real(log(result_conv(y+1,x)));
593        peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
594    else
595        F=-2; % warning flag for vector truncated by the limited search box
596    end
597    peakx=x;
598    if x <= npx-1 && x >= 1
599        f0 = log(result_conv(y,x));
600        f1 = real(log(result_conv(y,x-1)));
601        f2 = real(log(result_conv(y,x+1)));
602        peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
603    else
604        F=-2; % warning flag for vector truncated by the limited search box
605    end
606    vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
607
608%------------------------------------------------------------------------
609% --- Find the maximum of the correlation function after interpolation
610function [vector,F] = SUBPIX2DGAUSS (result_conv,x,y)
611%------------------------------------------------------------------------
612vector=[0 0]; %default
613F=-2;
614peaky=y;
615peakx=x;
616[npy,npx]=size(result_conv);
617if (x <= npx-1) && (y <= npy-1) && (x >= 1) && (y >= 1)
618    F=0;
619    for i=-1:1
620        for j=-1:1
621            %following 15 lines based on
622            %H. Nobach ï¿œ M. Honkanen (2005)
623            %Two-dimensional Gaussian regression for sub-pixel displacement
624            %estimation in particle image velocimetry or particle position
625            %estimation in particle tracking velocimetry
626            %Experiments in Fluids (2005) 38: 511ï¿œ515
627            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
628            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
629            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
630            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
631            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
632        end
633    end
634    c10=(1/6)*sum(sum(c10));
635    c01=(1/6)*sum(sum(c01));
636    c11=(1/4)*sum(sum(c11));
637    c20=(1/6)*sum(sum(c20));
638    c02=(1/6)*sum(sum(c02));
639    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11^2);
640    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11^2);
641    if abs(deltax)<1
642        peakx=x+deltax;
643    end
644    if abs(deltay)<1
645        peaky=y+deltay;
646    end
647end
648vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
649
650%'RUN_FIX': function for fixing velocity fields:
651%-----------------------------------------------
652% RUN_FIX(filename,field,flagindex,thresh_vecC,thresh_vel,iter,flag_mask,maskname,fileref,fieldref)
653%
654%filename: name of the netcdf file (used as input and output)
655%field: structure specifying the names of the fields to fix (depending on civ1 or civ2)
656    %.vel_type='civ1' or 'civ2';
657    %.nb=name of the dimension common to the field to fix ('nb_vectors' for civ1);
658    %.fixflag=name of fix flag variable ('vec_FixFlag' for civ1)
659%flagindex: flag specifying which values of vec_f are removed:
660        % if flagindex(1)=1: vec_f=-2 vectors are removed
661        % if flagindex(2)=1: vec_f=3 vectors are removed
662        % if flagindex(3)=1: vec_f=2 vectors are removed (if iter=1) or vec_f=4 vectors are removed (if iter=2)
663%iter=1 for civ1 fields and iter=2 for civ2 fields
664%thresh_vecC: threshold in the image correlation vec_C
665%flag_mask: =1 mask used to remove vectors (0 else)
666%maskname: name of the mask image file for fix
667%thresh_vel: threshold on velocity, or on the difference with the reference file fileref if exists
668%inf_sup=1: remove values smaller than threshold thresh_vel, =2, larger than threshold
669%fileref: .nc file name for a reference velocity (='': refrence 0 used)
670%fieldref: 'civ1','filter1'...feld used in fileref
671
672function FF=fix(Param,F,C,U,V,X,Y)
673FF=zeros(size(F));%default
674
675%criterium on warn flags
676FlagName={'CheckFmin2','CheckF2','CheckF3','CheckF4'};
677FlagVal=[-2 2 3 4];
678for iflag=1:numel(FlagName)
679    if isfield(Param,FlagName{iflag}) && Param.(FlagName{iflag})
680        FF=(FF==1| F==FlagVal(iflag));
681    end
682end
683%criterium on correlation values
684if isfield (Param,'MinCorr')
685    FF=FF==1 | C<Param.MinCorr;
686end
687if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
688    Umod= U.*U+V.*V;
689    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
690        FF=FF==1 | Umod<(Param.MinVel*Param.MinVel);
691    end
692    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
693        FF=FF==1 | Umod>(Param.MaxVel*Param.MaxVel);
694    end
695end
696
697
698
699%------------------------------------------------------------------------
700% patch function
701% OUTPUT:
702% SubRangx,SubRangy(NbSubdomain,2): range (min, max) of the coordiantes x and y respectively, for each subdomain
703% nbpoints(NbSubdomain): number of source points for each subdomain
704% FF: false flags
705% U_smooth, V_smooth: filtered velocity components at the positions of the initial data
706% X_tps,Y_tps,U_tps,V_tps: positions and weight of the tps for each subdomain
707%
708% INPUT:
709% X, Y: set of coordinates of the initial data
710% U,V: set of velocity components of the initial data
711% Rho: smoothing parameter
712% Threshold: max diff accepted between smoothed and initial data
713% Subdomain: estimated number of data points in each subdomain
714
715function [SubRangx,SubRangy,nbpoints,FF,U_smooth,V_smooth,X_tps,Y_tps,U_tps,V_tps] =patch(X,Y,U,V,Rho,Threshold,SubDomain)
716%subdomain decomposition
717warning off
718U=reshape(U,[],1);
719V=reshape(V,[],1);
720X=reshape(X,[],1);
721Y=reshape(Y,[],1);
722nbvec=numel(X);
723NbSubDomain=ceil(nbvec/SubDomain);
724MinX=min(X);
725MinY=min(Y);
726MaxX=max(X);
727MaxY=max(Y);
728RangX=MaxX-MinX;
729RangY=MaxY-MinY;
730AspectRatio=RangY/RangX;
731NbSubDomainX=max(floor(sqrt(NbSubDomain/AspectRatio)),1);
732NbSubDomainY=max(floor(sqrt(NbSubDomain*AspectRatio)),1);
733NbSubDomain=NbSubDomainX*NbSubDomainY;
734SizX=RangX/NbSubDomainX;%width of subdomains
735SizY=RangY/NbSubDomainY;%height of subdomains
736CentreX=linspace(MinX+SizX/2,MaxX-SizX/2,NbSubDomainX);
737CentreY=linspace(MinY+SizY/2,MaxY-SizY/2,NbSubDomainY);
738[CentreX,CentreY]=meshgrid(CentreX,CentreY);
739CentreY=reshape(CentreY,1,[]);% Y positions of subdomain centres
740CentreX=reshape(CentreX,1,[]);% X positions of subdomain centres
741rho=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)
742U_tps_sub=zeros(length(X),NbSubDomain);%default spline
743V_tps_sub=zeros(length(X),NbSubDomain);%default spline
744U_smooth=zeros(length(X),1);
745V_smooth=zeros(length(X),1);
746
747nb_select=zeros(length(X),1);
748FF=zeros(length(X),1);
749check_empty=zeros(1,NbSubDomain);
750SubRangx=zeros(NbSubDomain,2);%initialise the positions of subdomains
751SubRangy=zeros(NbSubDomain,2);
752for isub=1:NbSubDomain
753    SubRangx(isub,:)=[CentreX(isub)-0.55*SizX CentreX(isub)+0.55*SizX];
754    SubRangy(isub,:)=[CentreY(isub)-0.55*SizY CentreY(isub)+0.55*SizY];
755    ind_sel_previous=[];
756    ind_sel=0;
757    while numel(ind_sel)>numel(ind_sel_previous) %increase the subdomain during four iterations at most
758        ind_sel_previous=ind_sel;
759        ind_sel=find(X>=SubRangx(isub,1) & X<=SubRangx(isub,2) & Y>=SubRangy(isub,1) & Y<=SubRangy(isub,2));
760        % if no vector in the subdomain, skip the subdomain
761        if isempty(ind_sel)
762            check_empty(isub)=1;   
763            U_tps(1,isub)=0;%define U_tps and V_tps by default
764            V_tps(1,isub)=0;
765            break
766            % if too few selected vectors, increase the subrange for next iteration
767        elseif numel(ind_sel)<SubDomain/4 && ~isequal( ind_sel,ind_sel_previous);
768            SubRangx(isub,1)=SubRangx(isub,1)-SizX/4;
769            SubRangx(isub,2)=SubRangx(isub,2)+SizX/4;
770            SubRangy(isub,1)=SubRangy(isub,1)-SizY/4;
771            SubRangy(isub,2)=SubRangy(isub,2)+SizY/4;
772        else
773           
774            [U_smooth_sub,U_tps_sub]=tps_coeff([X(ind_sel) Y(ind_sel)],U(ind_sel),rho);
775            [V_smooth_sub,V_tps_sub]=tps_coeff([X(ind_sel) Y(ind_sel)],V(ind_sel),rho);
776            UDiff=U_smooth_sub-U(ind_sel);
777            VDiff=V_smooth_sub-V(ind_sel);
778            NormDiff=UDiff.*UDiff+VDiff.*VDiff;
779            FF(ind_sel)=20*(NormDiff>Threshold);%put FF value to 20 to identify the criterium of elimmination
780            ind_ind_sel=find(FF(ind_sel)==0); % select the indices of ind_sel corresponding to the remaining vectors
781            % no value exceeds threshold, the result is recorded
782            if isequal(numel(ind_ind_sel),numel(ind_sel))
783                U_smooth(ind_sel)=U_smooth(ind_sel)+U_smooth_sub;
784                V_smooth(ind_sel)=V_smooth(ind_sel)+V_smooth_sub;
785                nbpoints(isub)=numel(ind_sel);
786                X_tps(1:nbpoints(isub),isub)=X(ind_sel);
787                Y_tps(1:nbpoints(isub),isub)=Y(ind_sel);
788                U_tps(1:nbpoints(isub)+3,isub)=U_tps_sub;
789                V_tps(1:nbpoints(isub)+3,isub)=V_tps_sub;         
790                nb_select(ind_sel)=nb_select(ind_sel)+1;
791                 display('good')
792                break
793                % too few selected vectors, increase the subrange for next iteration
794            elseif numel(ind_ind_sel)<SubDomain/4 && ~isequal( ind_sel,ind_sel_previous);
795                SubRangx(isub,1)=SubRangx(isub,1)-SizX/4;
796                SubRangx(isub,2)=SubRangx(isub,2)+SizX/4;
797                SubRangy(isub,1)=SubRangy(isub,1)-SizY/4;
798                SubRangy(isub,2)=SubRangy(isub,2)+SizY/4;
799%                 display('fewsmooth')
800                % interpolation-smoothing is done again with the selected vectors
801            else
802                [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);
803                [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);
804                U_smooth(ind_sel(ind_ind_sel))=U_smooth(ind_sel(ind_ind_sel))+U_smooth_sub;
805                V_smooth(ind_sel(ind_ind_sel))=V_smooth(ind_sel(ind_ind_sel))+V_smooth_sub;
806                nbpoints(isub)=numel(ind_ind_sel);
807                X_tps(1:nbpoints(isub),isub)=X(ind_sel(ind_ind_sel));
808                Y_tps(1:nbpoints(isub),isub)=Y(ind_sel(ind_ind_sel));
809                U_tps(1:nbpoints(isub)+3,isub)=U_tps_sub;
810                V_tps(1:nbpoints(isub)+3,isub)=V_tps_sub;
811                nb_select(ind_sel(ind_ind_sel))=nb_select(ind_sel(ind_ind_sel))+1;
812                display('good2')
813                break
814            end
815        end
816    end
817end
818ind_empty=find(check_empty);
819%remove empty subdomains
820if ~isempty(ind_empty)
821    SubRangx(ind_empty,:)=[];
822    SubRangy(ind_empty,:)=[];
823    X_tps(:,ind_empty)=[];
824    Y_tps(:,ind_empty)=[];
825    U_tps(:,ind_empty)=[];
826    V_tps(:,ind_empty)=[];
827end
828nb_select(nb_select==0)=1;%ones(size(find(nb_select==0)));
829U_smooth=U_smooth./nb_select;
830V_smooth=V_smooth./nb_select;
831
832
833
834
835
Note: See TracBrowser for help on using the repository browser.