source: trunk/src/civ_matlab.m @ 382

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

several bugs corrected
function filter_tps introduced (spline thin shell)

File size: 30.3 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%   filter_tps: 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_SubRange','Civ1_NbSites','Civ1_Coord_tps','Civ1_U_tps','Civ1_V_tps'}];
172    Data.VarDimName=[Data.VarDimName {'NbVec1','NbVec1',{'NbCoord','Two','NbSubDomain1'},{'NbSubDomain1'},...
173             {'NbVec1Sub','NbCoord','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%     [SubRange,NbPoints,Coord_tps,U_tps,V_tps,W_tps,U_smooth,V_smooth,W_smooth,FF]
185    [Data.Civ1_SubRange,Data.Civ1_NbSites,Data.Civ1_Coord_tps,Data.Civ1_U_tps,Data.Civ1_V_tps,tild,Ures, Vres,tild,FFres]=...
186                            filter_tps([Data.Civ1_X(ind_good) Data.Civ1_Y(ind_good)],Data.Civ1_U(ind_good),Data.Civ1_V(ind_good),[],Data.Patch1_SubDomain,Data.Patch1_Threshold,Data.Patch1_Rho);
187      Data.Civ1_U_Diff(ind_good)=Data.Civ1_U(ind_good)-Ures;
188      Data.Civ1_V_Diff(ind_good)=Data.Civ1_V(ind_good)-Vres;
189      Data.Civ1_FF(ind_good)=FFres;
190      Data.CivStage=3;                             
191end   
192
193%% Civ2
194if isfield (Param,'Civ2')
195    par_civ2=Param.Civ2;
196    if ~isfield (Param,'Civ1') || ~strcmp(Param.Civ1.ImageA,par_civ2.ImageA)
197        par_civ2.ImageA=imread(Param.Civ2.ImageA);%read first image if not already done for civ1
198    else
199        par_civ2.ImageA=par_civ1.ImageA;
200    end
201    if ~isfield (Param,'Civ1') || ~strcmp(Param.Civ1.ImageB,par_civ2.ImageB)
202        par_civ2.ImageB=imread(Param.Civ2.ImageB);%read second image if not already done for civ1
203         else
204        par_civ2.ImageB=par_civ1.ImageB;
205    end
206    ibx2=ceil(par_civ2.Bx/2);
207    iby2=ceil(par_civ2.By/2);
208    isx2=ibx2+5;% search ara +-5 pixels around the guess
209    isy2=iby2+5;
210    % shift from par_civ2.filename_nc1
211    % shiftx=velocity interpolated at position
212    miniy=max(1+isy2,1+iby2);
213    minix=max(1+isx2,1+ibx2);
214    maxiy=min(size(par_civ2.ImageA,1)-isy2,size(par_civ2.ImageA,1)-iby2);
215    maxix=min(size(par_civ2.ImageA,2)-isx2,size(par_civ2.ImageA,2)-ibx2);
216    [GridX,GridY]=meshgrid(minix:par_civ2.Dx:maxix,miniy:par_civ2.Dy:maxiy);
217    GridX=reshape(GridX,[],1);
218    GridY=reshape(GridY,[],1);
219    Shiftx=zeros(size(GridX));% shift expected from civ1 data
220    Shifty=zeros(size(GridX));
221    nbval=zeros(size(GridX));
222    if par_civ2.CheckDeformation
223        DUDX=zeros(size(GridX));
224        DUDY=zeros(size(GridX));
225        DVDX=zeros(size(GridX));
226        DVDY=zeros(size(GridX));
227    end
228    [NbSubDomain,xx]=size(Data.Civ1_X_SubRange);
229    % get the guess from patch1
230    for isub=1:NbSubDomain
231        nbvec_sub=Data.Civ1_NbSites(isub);
232        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));
233        epoints = [GridX(ind_sel) GridY(ind_sel)];% coordinates of interpolation sites
234        ctrs=[Data.Civ1_X_tps(1:nbvec_sub,isub) Data.Civ1_Y_tps(1:nbvec_sub,isub)];%(=initial points) ctrs
235        nbval(ind_sel)=nbval(ind_sel)+1;% records the number of values for eacn interpolation point (in case of subdomain overlap)
236        EM = tps_eval(epoints,ctrs);
237        Shiftx(ind_sel)=Shiftx(ind_sel)+EM*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
238        Shifty(ind_sel)=Shifty(ind_sel)+EM*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
239        if par_civ2.CheckDeformation
240            [EMDX,EMDY] = tps_eval_dxy(epoints,ctrs);%2D matrix of distances between extrapolation points epoints and spline centres (=site points) ctrs
241            DUDX(ind_sel)=DUDX(ind_sel)+EMDX*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
242            DUDY(ind_sel)=DUDY(ind_sel)+EMDY*Data.Civ1_U_tps(1:nbvec_sub+3,isub);
243            DVDX(ind_sel)=DVDX(ind_sel)+EMDX*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
244            DVDY(ind_sel)=DVDY(ind_sel)+EMDY*Data.Civ1_V_tps(1:nbvec_sub+3,isub);
245        end
246    end
247    mask='';
248    if par_civ2.CheckMask&&~isempty(par_civ2.maskname)&& ~strcmp(maskname,par_civ2.maskname)% mask exist, not already read in civ1
249        mask=imread(par_civ2.maskname);
250    end
251    par_civ2.Searchx=2*isx2+1;
252    par_civ2.Searchy=2*isy2+1;
253    par_civ2.Shiftx=Shiftx(nbval>=1)./nbval(nbval>=1);
254    par_civ2.Shifty=Shifty(nbval>=1)./nbval(nbval>=1);
255    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   
256    if par_civ2.CheckDeformation
257        par_civ2.DUDX=DUDX./nbval;
258        par_civ2.DUDY=DUDY./nbval;
259        par_civ2.DVDX=DVDX./nbval;
260        par_civ2.DVDY=DVDY./nbval;
261    end
262    % caluclate velocity data (y and v in indices, reverse to y component)
263    [xtable ytable utable vtable ctable F] = civ (par_civ2);
264%     diff_squared=(utable-par_civ2.Shiftx).*(utable-par_civ2.Shiftx)+(vtable+par_civ2.Shifty).*(vtable+par_civ2.Shifty);
265%     F(diff_squared>=4)=4; %flag vectors whose distance to the guess exceeds 2 pixels
266    list_param=(fieldnames(Param.Civ2))';
267    list_remove={'pxcmx','pxcmy','npx','npy','gridflag','maskflag','term_a','term_b','T0'};
268    for ilist=1:length(list_remove)
269        index=strcmp(list_remove{ilist},list_param);
270        if ~isempty(find(index,1))
271            list_param(index)=[];
272        end
273    end
274    for ilist=1:length(list_param)
275        Civ2_param{ilist}=['Civ2_' list_param{ilist}];
276        eval(['Data.Civ2_' list_param{ilist} '=Param.Civ2.' list_param{ilist} ';'])
277    end
278    if isfield(Data,'Civ2_gridname') && strcmp(Data.Civ1_gridname(1:6),'noFile')
279        Data.Civ1_gridname='';
280    end
281    if isfield(Data,'Civ2_maskname') && strcmp(Data.Civ1_maskname(1:6),'noFile')
282        Data.Civ2_maskname='';
283    end
284    Data.ListGlobalAttribute=[Data.ListGlobalAttribute Civ2_param {'Civ2_Time','Civ2_Dt'}];
285%     Data.Civ2_Time=par_civ2.Time;
286%     Data.Civ2_Dt=par_civ2.Dt;
287    nbvar=numel(Data.ListVarName);
288    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
289    Data.VarDimName=[Data.VarDimName {'NbVec2','NbVec2','NbVec2','NbVec2','NbVec2','NbVec2'}];
290    Data.VarAttribute{nbvar+1}.Role='coord_x';
291    Data.VarAttribute{nbvar+2}.Role='coord_y';
292    Data.VarAttribute{nbvar+3}.Role='vector_x';
293    Data.VarAttribute{nbvar+4}.Role='vector_y';
294    Data.VarAttribute{nbvar+5}.Role='warnflag';
295    Data.Civ2_X=reshape(xtable,[],1);
296    Data.Civ2_Y=reshape(size(par_civ2.ImageA,1)-ytable+1,[],1);
297    Data.Civ2_U=reshape(utable,[],1);
298    Data.Civ2_V=reshape(-vtable,[],1);
299    Data.Civ2_C=reshape(ctable,[],1);
300    Data.Civ2_F=reshape(F,[],1);
301    Data.CivStage=Data.CivStage+1;
302end
303
304%% Fix2
305if isfield (Param,'Fix2')
306    ListFixParam=fieldnames(Param.Fix2);
307    for ilist=1:length(ListFixParam)
308        ParamName=ListFixParam{ilist};
309        ListName=['Fix2_' ParamName];
310        eval(['Data.ListGlobalAttribute=[Data.ListGlobalAttribute ''' ParamName '''];'])
311        eval(['Data.' ListName '=Param.Fix2.' ParamName ';'])
312    end
313    if check_civx
314        if ~isfield(Data,'fix2')
315            Data.ListGlobalAttribute=[Data.ListGlobalAttribute 'fix2'];
316            Data.fix2=1;
317            Data.ListVarName=[Data.ListVarName {'vec2_FixFlag'}];
318            Data.VarDimName=[Data.VarDimName {'nb_vectors2'}];
319        end
320        Data.vec_FixFlag=fix(Param.Fix2,Data.vec2_F,Data.vec2_C,Data.vec2_U,Data.vec2_V,Data.vec2_X,Data.vec2_Y);
321    else
322        Data.ListVarName=[Data.ListVarName {'Civ2_FF'}];
323        Data.VarDimName=[Data.VarDimName {'nbvec2'}];
324        nbvar=length(Data.ListVarName);
325        Data.VarAttribute{nbvar}.Role='errorflag';   
326        Data.Civ2_FF=fix(Param.Fix2,Data.Civ2_F,Data.Civ2_C,Data.Civ2_U,Data.Civ2_V);
327        Data.CivStage=Data.CivStage+1;   
328    end
329   
330end   
331
332%% Patch2
333if isfield (Param,'Patch2')
334    Data.ListGlobalAttribute=[Data.ListGlobalAttribute {'Patch2_Rho','Patch2_Threshold','Patch2_SubDomain'}];
335    Data.Patch2_Rho=Param.Patch2.SmoothingParam;
336    Data.Patch2_Threshold=Param.Patch2.MaxDiff;
337    Data.Patch2_SubDomain=Param.Patch2.SubdomainSize;
338    Data.ListVarName=[Data.ListVarName {'Civ2_U_Diff','Civ2_V_Diff','Civ2_X_SubRange','Civ2_Y_SubRange','Civ2_X_tps','Civ2_Y_tps','Civ2_U_tps','Civ2_V_tps','Civ2_Indices_tps'}];
339    Data.VarDimName=[Data.VarDimName {'NbVec2','NbVec2',{'NbSubDomain2','Two'},{'NbSubDomain2','Two'},...
340             {'NbVec2Sub','NbSubDomain2'},{'NbVec2Sub','NbSubDomain2'},{'Nbtps2','NbSubDomain2'},{'Nbtps2','NbSubDomain2'},{'NbVec2Sub','NbSubDomain2'}}];
341    nbvar=length(Data.ListVarName);
342    Data.VarAttribute{nbvar-1}.Role='vector_x';
343    Data.VarAttribute{nbvar}.Role='vector_y';
344    Data.Civ2_U_Diff=zeros(size(Data.Civ2_X));
345    Data.Civ2_V_Diff=zeros(size(Data.Civ2_X));
346    if isfield(Data,'Civ2_FF')
347        ind_good=find(Data.Civ2_FF==0);
348    else
349        ind_good=1:numel(Data.Civ2_X);
350    end
351    [Data.Civ2_SubRange,Data.Civ2_NbSites,Data.Civ2_Coord_tps,Data.Civ2_U_tps,Data.Civ2_V_tps,tild,Ures, Vres,tild,FFres]=...
352                            filter_tps([Data.Civ2_X(ind_good) Data.Civ2_Y(ind_good)],Data.Civ2_U(ind_good),Data.Civ2_V(ind_good),Data.Patch2_SubDomain,Data.Patch2_Rho,Data.Patch2_Threshold);
353      Data.Civ2_U_Diff(ind_good)=Data.Civ2_U(ind_good)-Ures;
354      Data.Civ2_V_Diff(ind_good)=Data.Civ2_V(ind_good)-Vres;
355      Data.Civ2_FF(ind_good)=FFres;
356      Data.CivStage=Data.CivStage+1;                             
357end 
358
359%% write result in a netcdf file if requested
360if exist('ncfile','var')
361    errormsg=struct2nc(ncfile,Data);
362end
363
364% 'civ': function piv.m adapted from PIVlab http://pivlab.blogspot.com/
365%--------------------------------------------------------------------------
366% function [xtable ytable utable vtable typevector] = civ (image1,image2,ibx,iby step, subpixfinder, mask, roi)
367%
368% OUTPUT:
369% xtable: set of x coordinates
370% ytable: set of y coordiantes
371% utable: set of u displacements (along x)
372% vtable: set of v displacements (along y)
373% ctable: max image correlation for each vector
374% typevector: set of flags, =1 for good, =0 for NaN vectors
375%
376%INPUT:
377% image1:first image (matrix)
378% image2: second image (matrix)
379% ibx2,iby2: half size of the correlation box along x and y, in px (size=(2*iby2+1,2*ibx2+1)
380% isx2,isy2: half size of the search box along x and y, in px (size=(2*isy2+1,2*isx2+1)
381% shiftx, shifty: shift of the search box (in pixel index, yshift reversed)
382% step: mesh of the measurement points (in px)
383% subpixfinder=1 or 2 controls the curve fitting of the image correlation
384% mask: =[] for no mask
385% roi: 4 element vector defining a region of interest: x position, y position, width, height, (in image indices), for the whole image, roi=[];
386function [xtable ytable utable vtable ctable F result_conv errormsg] = civ (par_civ)
387%this funtion performs the DCC PIV analysis. Recent window-deformation
388%methods perform better and will maybe be implemented in the future.
389
390%% prepare grid
391ibx2=ceil(par_civ.Bx/2);
392iby2=ceil(par_civ.By/2);
393isx2=ceil(par_civ.Searchx/2);
394isy2=ceil(par_civ.Searchy/2);
395shiftx=round(par_civ.Shiftx);
396shifty=-round(par_civ.Shifty);% sign minus because image j index increases when y decreases
397if isfield(par_civ,'Grid')
398    if ischar(par_civ.Grid)%read the drid file if the input is a file name
399        par_civ.Grid=dlmread(par_civ.Grid);
400        par_civ.Grid(1,:)=[];%the first line must be removed (heading in the grid file)
401    end
402else% automatic measurement grid
403    ibx2=ceil(par_civ.Bx/2);
404    iby2=ceil(par_civ.By/2);
405    isx2=ceil(par_civ.Searchx/2);
406    isy2=ceil(par_civ.Searchy/2);
407    miniy=max(1+isy2+shifty,1+iby2);
408    minix=max(1+isx2-shiftx,1+ibx2);
409    maxiy=min(par_civ.ImageHeight-isy2+shifty,par_civ.ImageHeight-iby2);
410    maxix=min(par_civ.ImageWidth-isx2-shiftx,par_civ.ImageWidth-ibx2);
411    [GridX,GridY]=meshgrid(minix:par_civ.Dx:maxix,miniy:par_civ.Dy:maxiy);
412    par_civ.Grid(:,1)=reshape(GridX,[],1);
413    par_civ.Grid(:,2)=reshape(GridY,[],1);
414end
415nbvec=size(par_civ.Grid,1);
416if numel(shiftx)==1
417    shiftx=shiftx*ones(nbvec,1);
418    shifty=shifty*ones(nbvec,1);
419end
420%% Default output
421xtable=par_civ.Grid(:,1);
422ytable=par_civ.Grid(:,2);
423utable=zeros(nbvec,1);
424vtable=zeros(nbvec,1);
425ctable=zeros(nbvec,1);
426F=zeros(nbvec,1);
427result_conv=[];
428errormsg='';
429
430%% prepare mask
431if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
432    if strcmp(par_civ.Mask,'all')
433        return    % get the grid only, no civ calculation
434    elseif ischar(par_civ.Mask)
435        par_civ.Mask=imread(par_civ.Mask);
436    end
437end
438check_MinIma=isfield(par_civ,'MinIma');% test for image luminosity threshold
439check_MaxIma=isfield(par_civ,'MaxIma') && ~isempty(par_civ.MaxIma);
440
441% %% prepare images
442% if isfield(par_civ,'reverse_pair')
443%     if par_civ.reverse_pair
444%         if ischar(par_civ.ImageB)
445%             temp=par_civ.ImageA;
446%             par_civ.ImageA=imread(par_civ.ImageB);
447%         end
448%         if ischar(temp)
449%             par_civ.ImageB=imread(temp);
450%         end
451%     end
452% else
453%     if ischar(par_civ.ImageA)
454%         par_civ.ImageA=imread(par_civ.ImageA);
455%     end
456%     if ischar(par_civ.ImageB)
457%         par_civ.ImageB=imread(par_civ.ImageB);
458%     end
459% end
460
461[npy_ima npx_ima]=size(par_civ.ImageA);
462if ~isequal(size(par_civ.ImageB),[npy_ima npx_ima])
463    errormsg='image pair with unequal size';
464    return
465end
466par_civ.ImageA=double(par_civ.ImageA);
467par_civ.ImageB=double(par_civ.ImageB);
468
469
470%% Apply mask
471    % Convention for mask
472    % mask >200 : velocity calculated
473    %  200 >=mask>150;velocity not calculated, interpolation allowed (bad spots)
474    % 150>=mask >100: velocity not calculated, nor interpolated
475    %  100>=mask> 20: velocity not calculated, impermeable (no flux through mask boundaries) TO IMPLEMENT
476    %  20>=mask: velocity=0
477checkmask=0;
478if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
479   checkmask=1;
480   if ~isequal(size(par_civ.Mask),[npy_ima npx_ima])
481        errormsg='mask must be an image with the same size as the images';
482        return
483   end
484  %  check_noflux=(par_civ.Mask<100) ;%TODO: to implement
485    check_undefined=(par_civ.Mask<200 & par_civ.Mask>=100 );
486    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
487    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
488end
489
490%% compute image correlations: MAINLOOP on velocity vectors
491corrmax=0;
492sum_square=1;% default
493mesh=1;% default
494CheckDecimal=isfield(par_civ,'CheckDecimal')&& par_civ.CheckDecimal==1;
495if CheckDecimal
496    mesh=0.2;%mesh in pixels for subpixel image interpolation
497    CheckDeformation=isfield(par_civ,'CheckDeformation')&& par_civ.CheckDeformation==1;
498end
499% vector=[0 0];%default
500for ivec=1:nbvec
501    iref=round(par_civ.Grid(ivec,1)+0.5);% xindex on the image A for the middle of the correlation box
502    jref=round(par_civ.ImageHeight-par_civ.Grid(ivec,2)+0.5);% yindex on the image B for the middle of the correlation box
503    if ~(checkmask && par_civ.Mask(jref,iref)<=20) %velocity not set to zero by the black mask
504        if jref-iby2<1 || jref+iby2>par_civ.ImageHeight|| iref-ibx2<1 || iref+ibx2>par_civ.ImageWidth||...
505              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
506            F(ivec)=3;
507        else
508            image1_crop=par_civ.ImageA(jref-iby2:jref+iby2,iref-ibx2:iref+ibx2);%extract a subimage (correlation box) from image A
509            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
510            image1_mean=mean(mean(image1_crop));
511            image2_mean=mean(mean(image2_crop));
512            %threshold on image minimum
513            if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
514                F(ivec)=3;
515            end
516            %threshold on image maximum
517            if check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
518                F(ivec)=3;
519            end
520        end     
521        if F(ivec)~=3
522            image1_crop=image1_crop-image1_mean;%substract the mean
523            image2_crop=image2_crop-image2_mean;
524            if CheckDecimal
525                xi=(1:mesh:size(image1_crop,2));
526                yi=(1:mesh:size(image1_crop,1))';
527                if CheckDeformation
528                    [XI,YI]=meshgrid(xi-ceil(size(image1_crop,2)/2),yi-ceil(size(image1_crop,1)/2));
529                    XIant=XI-par_civ.DUDX(ivec)*XI-par_civ.DUDY(ivec)*YI+ceil(size(image1_crop,2)/2);
530                    YIant=YI-par_civ.DVDX(ivec)*XI-par_civ.DVDY(ivec)*YI+ceil(size(image1_crop,1)/2);
531                    image1_crop=interp2(image1_crop,XIant,YIant);
532                else
533                    image1_crop=interp2(image1_crop,xi,yi);
534                end
535                xi=(1:mesh:size(image2_crop,2));
536                yi=(1:mesh:size(image2_crop,1))';
537                image2_crop=interp2(image2_crop,xi,yi);
538            end
539            sum_square=sum(sum(image1_crop.*image1_crop));
540            %reference: Oliver Pust, PIV: Direct Cross-Correlation
541            result_conv= conv2(image2_crop,flipdim(flipdim(image1_crop,2),1),'valid');
542            corrmax= max(max(result_conv));
543            result_conv=(result_conv/corrmax)*255; %normalize, peak=always 255
544            %Find the correlation max, at 255
545            [y,x] = find(result_conv==255,1);
546            if ~isempty(y) && ~isempty(x)
547                try
548                    if par_civ.Rho==1
549                        [vector,F(ivec)] = SUBPIXGAUSS (result_conv,x,y);
550                    elseif par_civ.Rho==2
551                        [vector,F(ivec)] = SUBPIX2DGAUSS (result_conv,x,y);
552                    end
553                    utable(ivec)=vector(1)*mesh+shiftx(ivec);
554                    vtable(ivec)=vector(2)*mesh+shifty(ivec);                 
555                    xtable(ivec)=iref+utable(ivec)/2-0.5;% convec flow (velocity taken at the point middle from imgae 1 and 2)
556                    ytable(ivec)=jref+vtable(ivec)/2-0.5;% and position of pixel 1=0.5 (convention for image coordinates=0 at the edge)
557                    iref=round(xtable(ivec));% image index for the middle of the vector
558                    jref=round(ytable(ivec));
559                    if checkmask && par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100
560                        utable(ivec)=0;
561                        vtable(ivec)=0;
562                        F(ivec)=3;
563                    end
564                    ctable(ivec)=corrmax/sum_square;% correlation value
565                catch ME
566                    F(ivec)=3;
567                end
568            else
569                F(ivec)=3;
570            end
571        end
572    end
573   
574    %Create the vector matrix x, y, u, v
575end
576result_conv=result_conv*corrmax/(255*sum_square);% keep the last correlation matrix for output
577
578%------------------------------------------------------------------------
579% --- Find the maximum of the correlation function after interpolation
580function [vector,F] = SUBPIXGAUSS (result_conv,x,y)
581%------------------------------------------------------------------------
582vector=[0 0]; %default
583F=0;
584[npy,npx]=size(result_conv);
585
586% if (x <= (size(result_conv,1)-1)) && (y <= (size(result_conv,1)-1)) && (x >= 1) && (y >= 1)
587    %the following 8 lines are copyright (c) 1998, Uri Shavit, Roi Gurka, Alex Liberzon, Technion ï¿œ Israel Institute of Technology
588    %http://urapiv.wordpress.com
589    peaky = y;
590    if y <= npy-1 && y >= 1
591        f0 = log(result_conv(y,x));
592        f1 = real(log(result_conv(y-1,x)));
593        f2 = real(log(result_conv(y+1,x)));
594        peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
595    else
596        F=-2; % warning flag for vector truncated by the limited search box
597    end
598    peakx=x;
599    if x <= npx-1 && x >= 1
600        f0 = log(result_conv(y,x));
601        f1 = real(log(result_conv(y,x-1)));
602        f2 = real(log(result_conv(y,x+1)));
603        peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
604    else
605        F=-2; % warning flag for vector truncated by the limited search box
606    end
607    vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
608
609%------------------------------------------------------------------------
610% --- Find the maximum of the correlation function after interpolation
611function [vector,F] = SUBPIX2DGAUSS (result_conv,x,y)
612%------------------------------------------------------------------------
613vector=[0 0]; %default
614F=-2;
615peaky=y;
616peakx=x;
617[npy,npx]=size(result_conv);
618if (x <= npx-1) && (y <= npy-1) && (x >= 1) && (y >= 1)
619    F=0;
620    for i=-1:1
621        for j=-1:1
622            %following 15 lines based on
623            %H. Nobach ï¿œ M. Honkanen (2005)
624            %Two-dimensional Gaussian regression for sub-pixel displacement
625            %estimation in particle image velocimetry or particle position
626            %estimation in particle tracking velocimetry
627            %Experiments in Fluids (2005) 38: 511ï¿œ515
628            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
629            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
630            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
631            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
632            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
633        end
634    end
635    c10=(1/6)*sum(sum(c10));
636    c01=(1/6)*sum(sum(c01));
637    c11=(1/4)*sum(sum(c11));
638    c20=(1/6)*sum(sum(c20));
639    c02=(1/6)*sum(sum(c02));
640    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11^2);
641    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11^2);
642    if abs(deltax)<1
643        peakx=x+deltax;
644    end
645    if abs(deltay)<1
646        peaky=y+deltay;
647    end
648end
649vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
650
651%'RUN_FIX': function for fixing velocity fields:
652%-----------------------------------------------
653% RUN_FIX(filename,field,flagindex,thresh_vecC,thresh_vel,iter,flag_mask,maskname,fileref,fieldref)
654%
655%filename: name of the netcdf file (used as input and output)
656%field: structure specifying the names of the fields to fix (depending on civ1 or civ2)
657    %.vel_type='civ1' or 'civ2';
658    %.nb=name of the dimension common to the field to fix ('nb_vectors' for civ1);
659    %.fixflag=name of fix flag variable ('vec_FixFlag' for civ1)
660%flagindex: flag specifying which values of vec_f are removed:
661        % if flagindex(1)=1: vec_f=-2 vectors are removed
662        % if flagindex(2)=1: vec_f=3 vectors are removed
663        % if flagindex(3)=1: vec_f=2 vectors are removed (if iter=1) or vec_f=4 vectors are removed (if iter=2)
664%iter=1 for civ1 fields and iter=2 for civ2 fields
665%thresh_vecC: threshold in the image correlation vec_C
666%flag_mask: =1 mask used to remove vectors (0 else)
667%maskname: name of the mask image file for fix
668%thresh_vel: threshold on velocity, or on the difference with the reference file fileref if exists
669%inf_sup=1: remove values smaller than threshold thresh_vel, =2, larger than threshold
670%fileref: .nc file name for a reference velocity (='': refrence 0 used)
671%fieldref: 'civ1','filter1'...feld used in fileref
672
673function FF=fix(Param,F,C,U,V,X,Y)
674FF=zeros(size(F));%default
675
676%criterium on warn flags
677FlagName={'CheckFmin2','CheckF2','CheckF3','CheckF4'};
678FlagVal=[-2 2 3 4];
679for iflag=1:numel(FlagName)
680    if isfield(Param,FlagName{iflag}) && Param.(FlagName{iflag})
681        FF=(FF==1| F==FlagVal(iflag));
682    end
683end
684%criterium on correlation values
685if isfield (Param,'MinCorr')
686    FF=FF==1 | C<Param.MinCorr;
687end
688if (isfield(Param,'MinVel')&&~isempty(Param.MinVel))||(isfield (Param,'MaxVel')&&~isempty(Param.MaxVel))
689    Umod= U.*U+V.*V;
690    if isfield (Param,'MinVel')&&~isempty(Param.MinVel)
691        FF=FF==1 | Umod<(Param.MinVel*Param.MinVel);
692    end
693    if isfield (Param,'MaxVel')&&~isempty(Param.MaxVel)
694        FF=FF==1 | Umod>(Param.MaxVel*Param.MaxVel);
695    end
696end
697
698
699
700
701
702
703
Note: See TracBrowser for help on using the repository browser.