如何通过扫描找到图像中不规则形状物体的宽度和高度?

时间:2015-11-19 04:45:16

标签: matlab image-processing

我有一个分段图像,里面有不规则形状的物体。我想计算不规则形状物体的面积,宽度和高度。我扫描了图像并写了 enter image description here

i=imread('cameraman.tif');
[m n ]=size(i)
for i=1:m
for j=1:n

如何检查像素是黑色还是白色?根据我的逻辑,扫描行中的像素数是宽度,列中的像素数是高度,像素的总数是面积。逻辑是否正确?

我想要白色物体的宽度。

enter image description here

这是附加数据集的标记图像。如何将分割后的图像与此标记图像进行比较?与标记图像相比,使用滑动窗口查找分割图像的宽度和高度是否容易?我需要一个不使用regionprop函数的代码。

1 个答案:

答案 0 :(得分:4)

您可以使用regionprops查找每个白色斑点的边界矩形区域。如果你需要计算白色像素的数量,现在你可以从这里轻松详细说明。尝试后告诉我们。

img = imread('TcpZy.png');
imshow(img);

s = regionprops(img);

for i = 1:length(s)
    bb = s(i).BoundingBox;
    rectangle('Position', [bb(1),bb(2),bb(3),bb(4)],...
        'EdgeColor','r','LineWidth',1)
    fprintf('\ni = %d\tarea = %f', i,s(i).Area);
end

输出:

i = 1   area = 42.000000
i = 2   area = 52.000000
i = 3   area = 76.000000
i = 4   area = 92.000000
i = 5   area = 40.000000
i = 6   area = 99.000000
i = 7   area = 182.000000
i = 8   area = 103.000000

输出图片:

enter image description here

更新1:

我更新答案以使其完整。

clc; clear all;

img = imread('TcpZy.png');
imshow(img);

s = regionprops(img);
figure;

for i = 1:length(s)
    bb = s(i).BoundingBox;

    r1 = round(bb(2));
    c1 = round(bb(1));
    w = bb(3);
    h = bb(4);
    r2 = r1+h-1;
    c2 = c1+w-1;

    img2 = img(r1:r2,c1:c2);
    subplot(2,4,i);
    imshow(img2);

    nw = sum(img2(:));

    fprintf(['\ni = %d\tbbarea = %.1f\tsrow = %d\tscol = %d\theight = %d'...
        '\twidth = %d\twhite=%d'], i,s(i).Area,r1,c1,h,w,nw);
end

fprintf('\n');

输出:

i = 1   bbarea = 42.0   srow = 15   scol = 143  height = 7  width = 15  white = 42
i = 2   bbarea = 52.0   srow = 42   scol = 147  height = 5  width = 15  white = 52
i = 3   bbarea = 76.0   srow = 69   scol = 150  height = 6  width = 19  white = 76
i = 4   bbarea = 92.0   srow = 99   scol = 153  height = 7  width = 21  white = 92
i = 5   bbarea = 40.0   srow = 222  scol = 154  height = 10 width = 14  white = 40
i = 6   bbarea = 99.0   srow = 129  scol = 155  height = 8  width = 24  white = 99
i = 7   bbarea = 182.0  srow = 193  scol = 155  height = 11 width = 26  white = 182
i = 8   bbarea = 103.0  srow = 161  scol = 158  height = 8  width = 21  white = 103

因此bbareaArea的{​​{1}}参数会提供白色像素数(或ON像素数)。为了向您显示,我分别计算了每个区域中的白色像素数,它们是相同的。因此,如果您想要包含白色和黑色像素(或ON和OFF像素)的区域,您可以将每个BoundingBox的宽度和高度相乘。

输出图像:此图现在显示每个BoundingBox的摘录。

enter image description here

如果要查看区域的宽度和高度是否包围所有白色斑点,请尝试以下操作。

BoundingBox

输出:

clc; clear all;

img = imread('TcpZy.png');
imshow(img);

s = regionprops(img);
bb = vertcat(s(:).BoundingBox);

r1 = min(bb(:,2));
c1 = min(bb(:,1));
h = max(bb(:,2)+bb(:,4))-r1+1;
w = max(bb(:,1)+bb(:,3))-c1+1;
rectangle('Position', [c1,r1,w,h],...
        'EdgeColor','r','LineWidth',1);

fprintf('\nw = %d\th = %d',w,h);

输出图片:

enter image description here