2013-07-04 68 views
2

我一直在拍摄图像并在其上绘制轮廓。我需要计算的像素没有和他们太三类的位置(在MATLAB中)计算多边形上的像素数

  1. 像素是朝向弯道外侧
  2. 像素是弯道内侧
  3. 像素是在曲线的边界上。

我曾尝试在MATLAB中使用inpolygon。它可以计算内部和外部的像素,但不包括边界上的像素。在边界上,只有那些直接通过小网格中心的人才会被计算在内。我还需要计算轮廓通过小网格四条边中任何一条的那些像素。

请帮忙。 我已经提供了下面的代码。

%Polygon Plotting 
clc;clear all;close all; 
I = imread('cameraman.tif'); 
I = imresize(I,[100 100]); 
I = double(I(:,:,1)); 
imagesc(I,[0 255]);colormap(gray); 
axis([1 size(I,1) 1 size(I,2)]); 
[BW xi yi] = roipoly(); %select your own coordinates. 
X=xi; 
Y=yi; 
hold on; 
contour(BW,'r'); 
hold off; 
xa = 1 : size(I,2); 
ya = 1 : size(I,1); 
[x,y] = meshgrid(xa,ya); 
[in on] = inpolygon(x,y,X,Y); 
count1 = sum(sum(in)); 
count2 = size(I,1)*size(I,2) - count1; 
count3 = sum(sum(on)); 
%count1 = inside the polygon and on boundary 
%count2 = outside the polygon 
%count3 = on the boundary only 
inside = zeros(count1,2); 
outside = zeros(count2,2); 
onthecurve = zeros(count3,2); 
l=1;m=1;n=1; 

    for i = 1:size(I,1) 
     for j = 1:size(I,2) 
      if in(i,j)==1 
       inside(l,1)=i; 
       inside(l,2)=j; 
       l=l+1; 
      end 
      if in(i,j)==0 
       outside(m,1)= i; 
       outside(m,2)= j; 
       m = m+1; 
      end 
      if on(i,j)==1 
       onthecurve(n,1)= i; 
       onthecurve(n,2)= j; 
       n = n+1; 
      end 
     end 
    end 
figure,  
plot(inside(:,1),inside(:,2),'+g'); 
axis([1 size(I,1) 1 size(I,2)]); 
hold on 
plot(outside(:,1),outside(:,2),'+r'); 
hold on 
plot(onthecurve(:,1),onthecurve(:,2),'+b'); 
hold off 

请参见链接,如果正确不显示图片: 1. Original Image & Contour 2. Green - inside, Red - outside

如可以看出轮廓上的点不标记为蓝色。事实上,count3几乎总是给出0的输出。所以inpolygon在计算边界上的点方面效率不高。

我该如何修改我的代码以计算这些像素呢? 谢谢大家。

回答

1

您可以使用edge检测黑白BW)图像(在这种情况下,输入多边形)的边界。

%% Polygon Plotting 
I = imread('cameraman.tif'); 
imshow(I); 
inBW = roipoly(); % Select your own coordinates. 

%% Make BW matrices 
outBW = ~inBW; % Find 'out' 
edBW = edge(inBW); % Find the 'edge' 
inBW(edBW) = 0; % Remove edge from 'in' 
outBW(edBW) = 0; % Remove edge from 'out' 

%% Show result 
imshow(double(cat(3, inBW, edBW, outBW))) 

还表明,所有像素都包含在3套:

prod(size(I)) - sum(sum(inBW + outBW + edBW)) 

应该变成零。

希望它有帮助。

+0

谢谢!但我想在不使用边缘运算符的情况下执行此功能。任何其他建议表示赞赏。 – roni

+0

另一件事,我真的想要计算外部,内部和曲线上的像素。通过使用for循环,我已经足够容易完成了。然后我想显示这些图并将其与原始轮廓进行比较。但是它们并不相似。这是由于以下事实:在图像中,点(1,1)位于最左上角,而在Matlab中的矩阵中,(1,1)位于最左下角位置。如何在绘图命令中反转我的y轴? – roni

+0

如果你不想使用'edge'命令,你可以编写自己的边缘检测功能,我相当确定有很多边缘检测算法。关于将矩阵的索引与图像进行匹配,请查看['flipud'](http://www.mathworks.com/help/matlab/ref/flipud.html)。 – pm89