source: trunk/src/civ.m @ 1199

Last change on this file since 1199 was 1199, checked in by sommeria, 3 hours ago

bugs repaired

File size: 18.2 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 isscalar(shiftx)% 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=false;
109check_undefined=zeros(npy_ima, npx_ima);
110MinA=min(min(par_civ.ImageA));
111if isfield(par_civ,'Mask') && ~isempty(par_civ.Mask)
112    checkmask=true;
113    if ~isequal(size(par_civ.Mask),[npy_ima npx_ima])
114        errormsg='mask must be an image with the same size as the images';
115        return
116    end
117    check_undefined=(par_civ.Mask<200 & par_civ.Mask>=20 );
118end
119
120%% compute image correlations: MAINLOOP on velocity vectors
121sum_square=1;% default
122mesh=1;% default
123CheckDeformation=isfield(par_civ,'CheckDeformation')&& par_civ.CheckDeformation==1;
124if CheckDeformation
125    mesh=0.25;%mesh in pixels for subpixel image interpolation (x 4 in each direction)
126    par_civ.CorrSmooth=2;% use SUBPIX2DGAUSS (take into account more points near the max)
127end
128SearchRange_1=par_civ.SearchRange(1);
129SearchRange_2=par_civ.SearchRange(2);
130if par_civ.CorrSmooth~=0 % par_civ.CorrSmooth=0 implies no civ computation (just input image and grid points given)
131    parfor ivec=1:nbvec
132%         iref=round(par_civ.Grid(ivec,1));% xindex on the image A for the middle of the correlation box
133%         jref=round(npy_ima-par_civ.Grid(ivec,2));%  j index  for the middle of the correlation box in the image A
134         iref=xtable(ivec);% xindex on the image A for the middle of the correlation box
135         jref=ytable(ivec);%  j index  for the middle of the correlation box in the image A
136
137        FF(ivec)=0;
138        ibx2=floor(CorrBoxSizeX(ivec)/2);
139        iby2=floor(CorrBoxSizeY(ivec)/2);
140        isx2=ibx2+ceil(SearchRange_1);
141        isy2=iby2+ceil(SearchRange_2);
142        subrange1_x=iref-ibx2:iref+ibx2;% x indices defining the first subimage
143        subrange1_y=jref-iby2:jref+iby2;% y indices defining the first subimage
144        subrange2_x=iref+shiftx(ivec)-isx2:iref+shiftx(ivec)+isx2;%x indices defining the second subimage
145        subrange2_y=jref-shifty(ivec)-isy2:jref-shifty(ivec)+isy2;%y indices defining the second subimage
146        image1_crop=MinA*ones(numel(subrange1_y),numel(subrange1_x));% default value=min of image A
147        image2_crop=MinA*ones(numel(subrange2_y),numel(subrange2_x));% default value=min of image A
148        check1_x=subrange1_x>=1 & subrange1_x<=npx_ima;% check which points in the subimage 1 are contained in the initial image 1
149        check1_y=subrange1_y>=1 & subrange1_y<=npy_ima;
150        check2_x=subrange2_x>=1 & subrange2_x<=npx_ima;% check which points in the subimage 2 are contained in the initial image 2
151        check2_y=subrange2_y>=1 & subrange2_y<=npy_ima;
152        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
153        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
154        if checkmask
155            mask1_crop=ones(numel(subrange1_y),numel(subrange1_x));% default value=1 for mask
156            mask2_crop=ones(numel(subrange2_y),numel(subrange2_x));% default value=1 for mask
157            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
158            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
159            sizemask=sum(sum(mask1_crop))/(numel(subrange1_y)*numel(subrange1_x));%size of the masked part relative to the correlation sub-image
160            if sizemask > 1/2% eliminate point if more than half of the correlation box is masked
161                FF(ivec)=1; %
162                utable(ivec)=NaN;
163                vtable(ivec)=NaN;
164            else
165                image1_crop=image1_crop.*~mask1_crop;% put to zero the masked pixels (mask1_crop='true'=1)
166                image2_crop=image2_crop.*~mask2_crop;
167                image1_mean=mean(mean(image1_crop))/(1-sizemask);
168                image2_mean=mean(mean(image2_crop))/(1-sizemask);
169            end
170        else
171            image1_mean=mean(mean(image1_crop));
172            image2_mean=mean(mean(image2_crop));
173        end
174        %threshold on image minimum
175        if FF(ivec)==0
176            if check_MinIma && (image1_mean < par_civ.MinIma || image2_mean < par_civ.MinIma)
177                FF(ivec)=1;
178                %threshold on image maximum
179            elseif check_MaxIma && (image1_mean > par_civ.MaxIma || image2_mean > par_civ.MaxIma)
180                FF(ivec)=1;
181            end
182            if FF(ivec)==1
183                utable(ivec)=NaN;
184                vtable(ivec)=NaN;
185            else
186                %mask
187                if checkmask
188                    image1_crop=(image1_crop-image1_mean).*~mask1_crop;%substract the mean, put to zero the masked parts
189                    image2_crop=(image2_crop-image2_mean).*~mask2_crop;
190                else
191                    image1_crop=(image1_crop-image1_mean);
192                    image2_crop=(image2_crop-image2_mean);
193                end
194                %deformation
195                if CheckDeformation
196                    xi=(1:mesh:size(image1_crop,2));
197                    yi=(1:mesh:size(image1_crop,1))';
198                    [XI,YI]=meshgrid(xi-ceil(size(image1_crop,2)/2),yi-ceil(size(image1_crop,1)/2));
199                    XIant=XI-par_civ.DUDX(ivec)*XI+par_civ.DUDY(ivec)*YI+ceil(size(image1_crop,2)/2);
200                    YIant=YI+par_civ.DVDX(ivec)*XI-par_civ.DVDY(ivec)*YI+ceil(size(image1_crop,1)/2);
201                    image1_crop=interp2(image1_crop,XIant,YIant);
202                    image1_crop(isnan(image1_crop))=0;
203                    xi=(1:mesh:size(image2_crop,2));
204                    yi=(1:mesh:size(image2_crop,1))';
205                    image2_crop=interp2(image2_crop,xi,yi,'*spline');
206                    image2_crop(isnan(image2_crop))=0;
207                end
208                sum_square=sum(sum(image1_crop.*image1_crop));
209                %reference: Oliver Pust, PIV: Direct Cross-Correlation
210                %%%%%% correlation calculation
211                result_conv= conv2(image2_crop,flip(flip(image1_crop,2),1),'valid');
212                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
213                corrmax= max(max(result_conv));
214               
215                %result_conv=(result_conv/corrmax); %normalize, peak=always 255
216                %Find the correlation max, at 255
217                [y,x] = find(result_conv==corrmax,1);
218                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
219                sum_square=sum_square*sum(sum(subimage2_crop.*subimage2_crop));% product of variances of image 1 and 2
220                sum_square=sqrt(sum_square);% srt of the variance product to normalise correlation
221                if ~isempty(y) && ~isempty(x)
222                    try
223                        if par_civ.CorrSmooth==1
224                            [vector,FF(ivec)] = SUBPIXGAUSS (result_conv,x,y);
225                        elseif par_civ.CorrSmooth==2
226                            [vector,FF(ivec)] = SUBPIX2DGAUSS (result_conv,x,y);
227                        else
228                            [vector,FF(ivec)] = quadr_fit(result_conv,x,y);
229                        end
230                        utable(ivec)=vector(1)*mesh+shiftx(ivec);
231                        vtable(ivec)=-vector(2)*mesh+shifty(ivec);% vtable and shifty in image coordinates (opposite to pixel shift)
232                      %  xtable(ivec)=iref+utable(ivec)/2-0.5;% convec flow (velocity taken at the point middle from imgae 1 and 2)
233                       % ytable(ivec)=jref+vtable(ivec)/2-0.5;% and position of pixel 1=0.5 (convention for image coordinates=0 at the edge)
234%                         iref=round(xtable(ivec)+0.5);% nearest image index for the middle of the vector
235%                         jref=round(ytable(ivec)+0.5);
236                        % eliminate vectors located in the mask
237%                         if  checkmask && (iref<1 || jref<1 ||iref>npx_ima || jref>npy_ima ||( par_civ.Mask(jref,iref)<200 && par_civ.Mask(jref,iref)>=100))
238%                             utable(ivec)=0;
239%                             vtable(ivec)=0;
240%                             FF(ivec)=1;
241%                         end
242                        ctable(ivec)=corrmax/sum_square;% correlation value
243                    catch ME
244                        FF(ivec)=1;
245                        disp(ME.message)
246                    end
247                else
248                    FF(ivec)=1;
249                end
250            end
251        end
252    end
253end
254ytable=npy_ima-ytable+1;%reverse from j index to image coordinate y
255result_conv=result_conv/sum_square;% keep the last correlation matrix for output
256
257
258
259%------------------------------------------------------------------------
260% --- Find the maximum of the correlation function with subpixel resolution
261% make a fit with a gaussian curve from the three correlation values across the max, along each direction.
262% OUPUT:
263% vector = optimum displacement vector with subpixel correction
264% FF =flag: =0 OK
265%           =1 , max too close to the edge of the search box (1 pixel margin)
266% INPUT:
267% result_conv: 2D correlation fct
268% x,y: position of the maximum correlation at integer values
269
270function [vector,FF] = SUBPIXGAUSS (result_conv,x,y)
271%------------------------------------------------------------------------
272% vector=[0 0]; %default
273FF=true;% error flag for vector truncated by the limited search box
274[npy,npx]=size(result_conv);
275
276peaky = y; peakx=x;
277if y < npy && y > 1 && x < npx-1 && x > 1
278    FF=false; % no error by the limited search box
279    max_conv=result_conv(y,x);% max correlation
280    %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
281    peak2noise=100;% TODO: make this threshold more precise, depending on the image noise
282    result_conv=result_conv*peak2noise/max_conv;% renormalise the correlation with respect to the noise
283    result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1  (=0 by discretisation, to avoid divergence in the log)
284   
285    f0 = log(result_conv(y,x));
286    f1 = log(result_conv(y-1,x));
287    f2 = log(result_conv(y+1,x));
288    peaky = peaky+ (f1-f2)/(2*f1-4*f0+2*f2);
289    f1 = log(result_conv(y,x-1));
290    f2 = log(result_conv(y,x+1));
291    peakx = peakx+ (f1-f2)/(2*f1-4*f0+2*f2);
292end
293
294vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
295
296%------------------------------------------------------------------------
297% --- Find the maximum of the correlation function after interpolation
298function [vector,FF] = SUBPIX2DGAUSS (result_conv,x,y)
299%------------------------------------------------------------------------
300% vector=[0 0]; %default
301FF=true;
302peaky=y;
303peakx=x;
304[npy,npx]=size(result_conv);
305if (x < npx) && (y < npy) && (x > 1) && (y > 1)
306    FF=false;
307max_conv=result_conv(y,x);% max correlation
308    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
309    result_conv=result_conv*peak2noise/max_conv;% renormalise the correlation with respect to the noise
310    result_conv(result_conv<1)=1; %set to 1 correlation values smaller than 1  (=0 by discretisation, to avoid divergence in the log)
311    for i=-1:1
312        for j=-1:1
313  %following 15 lines based on  H. Nobach and M. Honkanen (2005)
314  % Two-dimensional Gaussian regression for sub-pixel displacement
315  % estimation in particle image velocimetry or particle position
316  % estimation in particle tracking velocimetry
317  % Experiments in Fluids (2005) 38: 511-515
318            c10(j+2,i+2)=i*log(result_conv(y+j, x+i));
319            c01(j+2,i+2)=j*log(result_conv(y+j, x+i));
320            c11(j+2,i+2)=i*j*log(result_conv(y+j, x+i));
321            c20(j+2,i+2)=(3*i^2-2)*log(result_conv(y+j, x+i));
322            c02(j+2,i+2)=(3*j^2-2)*log(result_conv(y+j, x+i));
323        end
324    end
325    c10=(1/6)*sum(sum(c10));
326    c01=(1/6)*sum(sum(c01));
327    c11=(1/4)*sum(sum(c11));
328    c20=(1/6)*sum(sum(c20));
329    c02=(1/6)*sum(sum(c02));
330    deltax=(c11*c01-2*c10*c02)/(4*c20*c02-c11*c11);
331    deltay=(c11*c10-2*c01*c20)/(4*c20*c02-c11*c11);
332    if abs(deltax)<1
333        peakx=x+deltax;
334    end
335    if abs(deltay)<1
336        peaky=y+deltay;
337    end
338end
339vector=[peakx-floor(npx/2)-1 peaky-floor(npy/2)-1];
340
341%------------------------------------------------------------------------
342% --- Find the maximum of the correlation function after quadratic interpolation
343function [vector,F] = quadr_fit(result_conv,x,y)
344[npy,npx]=size(result_conv);
345if x<4 || y<4 || npx-x<4 ||npy-y <4
346    F=1;
347    vector=[x y];
348else
349    F=0;
350    x_ind=x-4:x+4;
351    y_ind=y-4:y+4;
352    x_vec=0.25*(x_ind-x);
353    y_vec=0.25*(y_ind-y);
354    [X,Y]=meshgrid(x_vec,y_vec);
355    coord=[reshape(X,[],1) reshape(Y,[],1)];
356    result_conv=reshape(result_conv(y_ind,x_ind),[],1);
357   
358   
359    % n=numel(X);
360    % x=[X Y];
361    % X=X-0.5;
362    % Y=Y+0.5;
363    % y = (X.*X+2*Y.*Y+X.*Y+6) + 0.1*rand(n,1);
364    p = polyfitn(coord,result_conv,2);
365    A(1,1)=2*p.Coefficients(1);
366    A(1,2)=p.Coefficients(2);
367    A(2,1)=p.Coefficients(2);
368    A(2,2)=2*p.Coefficients(4);
369    vector=[x y]'-A\[p.Coefficients(3) p.Coefficients(5)]';
370    vector=vector'-[floor(npx/2) floor(npy/2)]-1 ;
371    % zg = polyvaln(p,coord);
372    % figure
373    % surf(x_vec,y_vec,reshape(zg,9,9))
374    % hold on
375    % plot3(X,Y,reshape(result_conv,9,9),'o')
376    % hold off
377end
378
379
Note: See TracBrowser for help on using the repository browser.