source: trunk/src/civ.m @ 1195

Last change on this file since 1195 was 1195, checked in by sommeria, 5 days ago

format of PIV data made more compact/4

File size: 18.1 KB
Line 
1%--------------------------------------------------------------------------
2%  'civ': key function  for image correlations (called by series/cvi_series.m)
3% function [xtable ytable utable vtable typevector] = civ (image1,image2,ibx,iby step, subpixfinder, mask, roi)
4%
5% OUTPUT:
6% xtable: set of x positions of the first image in integer image coordinates , the measurement position is xtable-0.5+utable/2
7% ytable: set of y coordinates of the first image in integer image coordinates (starting in the image bottom, image index= npy-ytable+1 , the measurement position is ytable-0.5+vtable/2
8% utable: set of u displacements (along x), in pixels
9% vtable: set of v displacements (along y)
10% ctable: max image correlation for each vector
11% typevector: set of flags, =1 for good, =0 for NaN vectors
12%
13%INPUT:
14% par_civ: structure of input parameters, with fields:
15%  .ImageA: first image for correlation (matrix)
16%  .ImageB: second image for correlation(matrix)
17%  .CorrBoxSize: 1,2 vector giving the size of the correlation box in x and y
18%  .SearchBoxSize:  1,2 vector giving the size of the search box in x and y
19%  .SearchBoxShift: 1,2 vector or 2 column matrix (for civ2) giving the shift of the search box in x and y
20%  .CorrSmooth: =1 or 2 determines the choice of the sub-pixel determination of the correlation max
21%  .ImageWidth: nb of pixels of the image in x
22%  .Dx, Dy: mesh for the PIV calculation
23%  .Grid: grid giving the PIV calculation points (alternative to .Dx .Dy): centres of the correlation boxes in Image A
24%  .Mask: name of a mask file or mask image matrix itself
25%  .MinIma: thresholds for image luminosity
26%  .MaxIma
27%  .CheckDeformation=1 for subpixel interpolation and image deformation (linear transform)
28%  .DUDX: matrix of deformation obtained from patch at each grid point
29%  .DUDY
30%  .DVDX:
31%  .DVDY
32
33function [xtable,ytable,utable,vtable,ctable,FF,result_conv,errormsg] = civ (par_civ)
34
35%% check input images
36par_civ.ImageA=sum(double(par_civ.ImageA),3);%sum over rgb component for color images
37par_civ.ImageB=sum(double(par_civ.ImageB),3);
38[npy_ima,npx_ima]=size(par_civ.ImageA);
39if ~isequal(size(par_civ.ImageB),[npy_ima npx_ima])
40    errormsg='image pair with unequal size';
41    return
42end
43
44%% prepare measurement grid if not given as input
45if ~isfield(par_civ,'Grid')% grid points defining central positions of the sub-images in image A
46    nbinterv_x=floor((npx_ima-1)/par_civ.Dx);%expected number of intervals Dx
47    gridlength_x=nbinterv_x*par_civ.Dx;
48    minix=ceil((npx_ima-gridlength_x)/2);
49    nbinterv_y=floor((npy_ima-1)/par_civ.Dy);%expected number of intervals Dy
50    gridlength_y=nbinterv_y*par_civ.Dy;
51    miniy=ceil((npy_ima-gridlength_y)/2);
52    [GridX,GridY]=meshgrid(minix+0.5:par_civ.Dx:npx_ima-0.5,miniy+0.5:par_civ.Dy:npy_ima-0.5);% grid of initial positions in pixel coordinates (y upward)
53    par_civ.Grid(:,1)=reshape(GridX,[],1);
54    par_civ.Grid(:,2)=reshape(GridY,[],1);% increases with array index
55end
56nbvec=size(par_civ.Grid,1);
57
58
59%% prepare correlation and search boxes
60CorrBoxSizeX=par_civ.CorrBoxSize(:,1);
61CorrBoxSizeY=par_civ.CorrBoxSize(:,2);
62if size(par_civ.CorrBoxSize,1)==1
63    CorrBoxSizeX=par_civ.CorrBoxSize(1)*ones(nbvec,1);
64    CorrBoxSizeY=par_civ.CorrBoxSize(2)*ones(nbvec,1);
65end
66
67shiftx=par_civ.SearchBoxShift(:,1);%use the input shift estimate, rounded to the next integer value
68shifty=par_civ.SearchBoxShift(:,2);%
69if numel(shiftx)==1% case of a unique shift for the whole field( civ1)
70    shiftx=shiftx*ones(nbvec,1);
71    shifty=shifty*ones(nbvec,1);
72end
73
74%% shift the grid by half the expected displacement to get the velocity closer to the initial grid
75par_civ.Grid(:,1)=par_civ.Grid(:,1)-shiftx/2;% initial positions in image coordinates (y upward)
76par_civ.Grid(:,2)=par_civ.Grid(:,2)-shifty/2;
77
78%% Array initialisation and default output  if par_civ.CorrSmooth=0 (just the grid calculated, no civ computation)
79xtable=round(par_civ.Grid(:,1)+0.5);% tables of image indices corresponding to the input grid
80ytable=round(npy_ima-par_civ.Grid(:,2)+0.5);% y image indices corresponding to the position in image coordinates
81shiftx=round(shiftx);
82shifty=round(shifty);
83utable=shiftx;%zeros(nbvec,1);% expected displacements in pixel indices (y downward)
84vtable=-shifty;%zeros(nbvec,1);
85ctable=zeros(nbvec,1);
86FF=zeros(nbvec,1);
87result_conv=[];
88errormsg='';
89
90%% prepare mask
91if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
92    if strcmp(par_civ.Mask,'all')
93        return    % get the grid only, no civ calculation
94    elseif ischar(par_civ.Mask)
95        par_civ.Mask=imread(par_civ.Mask);% read the mask if not allready done
96    end
97end
98check_MinIma=isfield(par_civ,'MinIma');% test for image luminosity threshold
99check_MaxIma=isfield(par_civ,'MaxIma') && ~isempty(par_civ.MaxIma);
100
101%% Apply mask
102% Convention for mask, IDEAS NOT IMPLEMENTED
103% mask >200 : velocity calculated
104%  200 >=mask>150;velocity not calculated, interpolation allowed (bad spots)
105% 150>=mask >100: velocity not calculated, nor interpolated
106%  100>=mask> 20: velocity not calculated, impermeable (no flux through mask boundaries)
107%  20>=mask: velocity=0
108checkmask=0;
109MinA=min(min(par_civ.ImageA));
110if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
111    checkmask=1;
112    if ~isequal(size(par_civ.Mask),[npy_ima npx_ima])
113        errormsg='mask must be an image with the same size as the images';
114        return
115    end
116    check_undefined=(par_civ.Mask<200 & par_civ.Mask>=20 );
117end
118
119%% compute image correlations: MAINLOOP on velocity vectors
120sum_square=1;% default
121mesh=1;% default
122CheckDeformation=isfield(par_civ,'CheckDeformation')&& par_civ.CheckDeformation==1;
123if CheckDeformation
124    mesh=0.25;%mesh in pixels for subpixel image interpolation (x 4 in each direction)
125    par_civ.CorrSmooth=2;% use SUBPIX2DGAUSS (take into account more points near the max)
126end
127
128if par_civ.CorrSmooth~=0 % par_civ.CorrSmooth=0 implies no civ computation (just input image and grid points given)
129    for ivec=1:nbvec
130%         iref=round(par_civ.Grid(ivec,1));% xindex on the image A for the middle of the correlation box
131%         jref=round(npy_ima-par_civ.Grid(ivec,2));%  j index  for the middle of the correlation box in the image A
132         iref=xtable(ivec);% xindex on the image A for the middle of the correlation box
133         jref=ytable(ivec);%  j index  for the middle of the correlation box in the image A
134
135        FF(ivec)=0;
136        ibx2=floor(CorrBoxSizeX(ivec)/2);
137        iby2=floor(CorrBoxSizeY(ivec)/2);
138        isx2=ibx2+ceil(par_civ.SearchRange(1));
139        isy2=iby2+ceil(par_civ.SearchRange(2));
140        subrange1_x=iref-ibx2:iref+ibx2;% x indices defining the first subimage
141        subrange1_y=jref-iby2:jref+iby2;% y indices defining the first subimage
142        subrange2_x=iref+shiftx(ivec)-isx2:iref+shiftx(ivec)+isx2;%x indices defining the second subimage
143        subrange2_y=jref-shifty(ivec)-isy2:jref-shifty(ivec)+isy2;%y indices defining the second subimage
144        image1_crop=MinA*ones(numel(subrange1_y),numel(subrange1_x));% default value=min of image A
145        image2_crop=MinA*ones(numel(subrange2_y),numel(subrange2_x));% default value=min of image A
146        check1_x=subrange1_x>=1 & subrange1_x<=npx_ima;% check which points in the subimage 1 are contained in the initial image 1
147        check1_y=subrange1_y>=1 & subrange1_y<=npy_ima;
148        check2_x=subrange2_x>=1 & subrange2_x<=npx_ima;% check which points in the subimage 2 are contained in the initial image 2
149        check2_y=subrange2_y>=1 & subrange2_y<=npy_ima;
150        image1_crop(check1_y,check1_x)=par_civ.ImageA(subrange1_y(check1_y),subrange1_x(check1_x));%extract a subimage (correlation box) from image A
151        image2_crop(check2_y,check2_x)=par_civ.ImageB(subrange2_y(check2_y),subrange2_x(check2_x));%extract a larger subimage (search box) from image B
152        if checkmask
153            mask1_crop=ones(numel(subrange1_y),numel(subrange1_x));% default value=1 for mask
154            mask2_crop=ones(numel(subrange2_y),numel(subrange2_x));% default value=1 for mask
155            mask1_crop(check1_y,check1_x)=check_undefined(subrange1_y(check1_y),subrange1_x(check1_x));%extract a mask subimage (correlation box) from image A
156            mask2_crop(check2_y,check2_x)=check_undefined(subrange2_y(check2_y),subrange2_x(check2_x));%extract a mask subimage (search box) from image B
157            sizemask=sum(sum(mask1_crop))/(numel(subrange1_y)*numel(subrange1_x));%size of the masked part relative to the correlation sub-image
158            if sizemask > 1/2% eliminate point if more than half of the correlation box is masked
159                FF(ivec)=1; %
160                utable(ivec)=NaN;
161                vtable(ivec)=NaN;
162            else
163                image1_crop=image1_crop.*~mask1_crop;% put to zero the masked pixels (mask1_crop='true'=1)
164                image2_crop=image2_crop.*~mask2_crop;
165                image1_mean=mean(mean(image1_crop))/(1-sizemask);
166                image2_mean=mean(mean(image2_crop))/(1-sizemask);
167            end
168        else
169            image1_mean=mean(mean(image1_crop));
170            image2_mean=mean(mean(image2_crop));
171        end
172        %threshold on image minimum
173        if FF(ivec)==0
174            if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
175                FF(ivec)=1;
176                %threshold on image maximum
177            elseif check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
178                FF(ivec)=1;
179            end
180            if FF(ivec)==1
181                utable(ivec)=NaN;
182                vtable(ivec)=NaN;
183            else
184                %mask
185                if checkmask
186                    image1_crop=(image1_crop-image1_mean).*~mask1_crop;%substract the mean, put to zero the masked parts
187                    image2_crop=(image2_crop-image2_mean).*~mask2_crop;
188                else
189                    image1_crop=(image1_crop-image1_mean);
190                    image2_crop=(image2_crop-image2_mean);
191                end
192                %deformation
193                if CheckDeformation
194                    xi=(1:mesh:size(image1_crop,2));
195                    yi=(1:mesh:size(image1_crop,1))';
196                    [XI,YI]=meshgrid(xi-ceil(size(image1_crop,2)/2),yi-ceil(size(image1_crop,1)/2));
197                    XIant=XI-par_civ.DUDX(ivec)*XI+par_civ.DUDY(ivec)*YI+ceil(size(image1_crop,2)/2);
198                    YIant=YI+par_civ.DVDX(ivec)*XI-par_civ.DVDY(ivec)*YI+ceil(size(image1_crop,1)/2);
199                    image1_crop=interp2(image1_crop,XIant,YIant);
200                    image1_crop(isnan(image1_crop))=0;
201                    xi=(1:mesh:size(image2_crop,2));
202                    yi=(1:mesh:size(image2_crop,1))';
203                    image2_crop=interp2(image2_crop,xi,yi,'*spline');
204                    image2_crop(isnan(image2_crop))=0;
205                end
206                sum_square=sum(sum(image1_crop.*image1_crop));
207                %reference: Oliver Pust, PIV: Direct Cross-Correlation
208                %%%%%% correlation calculation
209                result_conv= conv2(image2_crop,flip(flip(image1_crop,2),1),'valid');
210                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
211                corrmax= max(max(result_conv));
212               
213                %result_conv=(result_conv/corrmax); %normalize, peak=always 255
214                %Find the correlation max, at 255
215                [y,x] = find(result_conv==corrmax,1);
216                subimage2_crop=image2_crop(y:y+2*iby2/mesh,x:x+2*ibx2/mesh);%subimage of image 2 corresponding to the optimum displacement of first image
217                sum_square=sum_square*sum(sum(subimage2_crop.*subimage2_crop));% product of variances of image 1 and 2
218                sum_square=sqrt(sum_square);% srt of the variance product to normalise correlation
219                if ~isempty(y) && ~isempty(x)
220                    try
221                        if par_civ.CorrSmooth==1
222                            [vector,FF(ivec)] = SUBPIXGAUSS (result_conv,x,y);
223                        elseif par_civ.CorrSmooth==2
224                            [vector,FF(ivec)] = SUBPIX2DGAUSS (result_conv,x,y);
225                        else
226                            [vector,FF(ivec)] = quadr_fit(result_conv,x,y);
227                        end
228                        utable(ivec)=vector(1)*mesh+shiftx(ivec);
229                        vtable(ivec)=-vector(2)*mesh+shifty(ivec);% vtable and shifty in image coordinates (opposite to pixel shift)
230                      %  xtable(ivec)=iref+utable(ivec)/2-0.5;% convec flow (velocity taken at the point middle from imgae 1 and 2)
231                       % ytable(ivec)=jref+vtable(ivec)/2-0.5;% and position of pixel 1=0.5 (convention for image coordinates=0 at the edge)
232%                         iref=round(xtable(ivec)+0.5);% nearest image index for the middle of the vector
233%                         jref=round(ytable(ivec)+0.5);
234                        % eliminate vectors located in the mask
235%                         if  checkmask && (iref<1 || jref<1 ||iref>npx_ima || jref>npy_ima ||( par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100))
236%                             utable(ivec)=0;
237%                             vtable(ivec)=0;
238%                             FF(ivec)=1;
239%                         end
240                        ctable(ivec)=corrmax/sum_square;% correlation value
241                    catch ME
242                        FF(ivec)=1;
243                        disp(ME.message)
244                    end
245                else
246                    FF(ivec)=1;
247                end
248            end
249        end
250    end
251end
252ytable=npy_ima-ytable+1;%reverse from j index to image coordinate y
253result_conv=result_conv/sum_square;% keep the last correlation matrix for output
254
255
256
257%------------------------------------------------------------------------
258% --- Find the maximum of the correlation function with subpixel resolution
259% make a fit with a gaussian curve from the three correlation values across the max, along each direction.
260% OUPUT:
261% vector = optimum displacement vector with subpixel correction
262% FF =flag: =0 OK
263%           =1 , max too close to the edge of the search box (1 pixel margin)
264% INPUT:
265% result_conv: 2D correlation fct
266% x,y: position of the maximum correlation at integer values
267
268function [vector,FF] = SUBPIXGAUSS (result_conv,x,y)
269%------------------------------------------------------------------------
270% vector=[0 0]; %default
271FF=true;% error flag for vector truncated by the limited search box
272[npy,npx]=size(result_conv);
273
274peaky = y; peakx=x;
275if y < npy && y > 1 && x < npx-1 && x > 1
276    FF=false; % no error by the limited search box
277    max_conv=result_conv(y,x);% max correlation
278    %peak2noise= max(4,max_conv/std(reshape(result_conv,1,[])));% ratio of max conv to standard deviation of correlations (estiamtion of noise level), set to value 4 if it is too low
279    peak2noise=100;% TODO: make this threshold more precise, depending on the image noise
280    result_conv=result_conv*peak2noise/max_conv;% renormalise the correlation with respect to the noise
281    result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1  (=0 by discretisation, to avoid divergence in the log)
282   
283    f0 = log(result_conv(y,x));
284    f1 = log(result_conv(y-1,x));
285    f2 = log(result_conv(y+1,x));
286    peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
287    f1 = log(result_conv(y,x-1));
288    f2 = log(result_conv(y,x+1));
289    peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
290end
291
292vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
293
294%------------------------------------------------------------------------
295% --- Find the maximum of the correlation function after interpolation
296function [vector,FF] = SUBPIX2DGAUSS (result_conv,x,y)
297%------------------------------------------------------------------------
298% vector=[0 0]; %default
299FF=true;
300peaky=y;
301peakx=x;
302[npy,npx]=size(result_conv);
303if (x < npx) && (y < npy) && (x > 1) && (y > 1)
304    FF=false;
305max_conv=result_conv(y,x);% max correlation
306    peak2noise= max(4,max_conv/std(reshape(result_conv,1,[])));% ratio of max conv to standard deviation of correlations (estiamtion of noise level), set to value 4 if it is too low
307    result_conv=result_conv*peak2noise/max_conv;% renormalise the correlation with respect to the noise
308    result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1  (=0 by discretisation, to avoid divergence in the log)
309    for i=-1:1
310        for j=-1:1
311  %following 15 lines based on  H. Nobach and M. Honkanen (2005)
312  % Two-dimensional Gaussian regression for sub-pixel displacement
313  % estimation in particle image velocimetry or particle position
314  % estimation in particle tracking velocimetry
315  % Experiments in Fluids (2005) 38: 511-515
316            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
317            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
318            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
319            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
320            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
321        end
322    end
323    c10=(1/6)*sum(sum(c10));
324    c01=(1/6)*sum(sum(c01));
325    c11=(1/4)*sum(sum(c11));
326    c20=(1/6)*sum(sum(c20));
327    c02=(1/6)*sum(sum(c02));
328    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11*c11);
329    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11*c11);
330    if abs(deltax)<1
331        peakx=x+deltax;
332    end
333    if abs(deltay)<1
334        peaky=y+deltay;
335    end
336end
337vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
338
339%------------------------------------------------------------------------
340% --- Find the maximum of the correlation function after quadratic interpolation
341function [vector,F] = quadr_fit(result_conv,x,y)
342[npy,npx]=size(result_conv);
343if x<4 || y<4 || npx-x<4 ||npy-y <4
344    F=1;
345    vector=[x y];
346else
347    F=0;
348    x_ind=x-4:x+4;
349    y_ind=y-4:y+4;
350    x_vec=0.25*(x_ind-x);
351    y_vec=0.25*(y_ind-y);
352    [X,Y]=meshgrid(x_vec,y_vec);
353    coord=[reshape(X,[],1) reshape(Y,[],1)];
354    result_conv=reshape(result_conv(y_ind,x_ind),[],1);
355   
356   
357    % n=numel(X);
358    % x=[X Y];
359    % X=X-0.5;
360    % Y=Y+0.5;
361    % y = (X.*X+2*Y.*Y+X.*Y+6) + 0.1*rand(n,1);
362    p = polyfitn(coord,result_conv,2);
363    A(1,1)=2*p.Coefficients(1);
364    A(1,2)=p.Coefficients(2);
365    A(2,1)=p.Coefficients(2);
366    A(2,2)=2*p.Coefficients(4);
367    vector=[x y]'-A\[p.Coefficients(3) p.Coefficients(5)]';
368    vector=vector'-[floor(npx/2) floor(npy/2)]-1 ;
369    % zg = polyvaln(p,coord);
370    % figure
371    % surf(x_vec,y_vec,reshape(zg,9,9))
372    % hold on
373    % plot3(X,Y,reshape(result_conv,9,9),'o')
374    % hold off
375end
376
377
Note: See TracBrowser for help on using the repository browser.