source: trunk/src/civ_matlab.m @ 387

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

several bugs corrected: mask, color image...

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