【问题标题】:Count the no of pixels on a polygon计算多边形上的像素数
【发布时间】:2013-07-02 18:49:48
【问题描述】:

我一直在拍摄图像并在其上绘制轮廓。我需要在三个类别中计算像素的数量和它们的位置(在 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 在计算边界上的点时效率不是很高。

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

【问题讨论】:

    标签: matlab contour boundary point-in-polygon


    【解决方案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))
    

    应该为零。

    希望对你有帮助。

    【讨论】:

    • 谢谢!但我想在不使用边缘运算符的情况下执行该功能。任何其他建议表示赞赏。
    • 我真的很想计算曲线外、内和曲线上的像素。通过使用 for 循环,我已经很容易做到了。然后我想显示这些图并将其与原始轮廓进行比较。然而它们并不相似。这是因为在 Image 中,点 (1,1) 位于最左上角,而在 Matlab 中的 Matrix 中,(1,1) 位于最左下角。如何在绘图命令中反转我的 y 轴?
    • 如果你不想使用edge命令你可以编写自己的边缘检测函数,我很确定有很多边缘检测算法。关于将矩阵的索引与图像匹配,请查看flipud
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 2013-04-19
    相关资源
    最近更新 更多