计算图像中前景和背景像素的数量

时间:2013-04-17 09:06:35

标签: matlab image-processing

以“B”字母为例:


如果我们绘制字母'B'的直线4侧,那么它将创建一个矩形框。我必须在上面的图片中找到此边界框(Recangle Box)中的前景和背景像素数。我没有得到结果。请帮助我。谢谢。

这是我的代码:

 E = imread('1.jpg');
 label = graythresh(E);
 BW = im2bw(E, label);
 imshow(BW)
 L = bwlabel(E);
 z = regionprops(L,'BoundingBox');
 nBlackpixel = sum(z(:))
 nWhitepixel = numel(z) - nBlack

2 个答案:

答案 0 :(得分:1)

尝试使用不同的属性

z = regionprops( L, 'Image' );
nFG = zeros(1,numel(z)); % pre-allocate
nBG = zeros(1,numel(z));
for ii=1:numel(z), % in case there are more than one object in the image
    nFG(ii) = nnz(z(ii).Image); % count number of FG pixels
    nBG(ii) = numel( z(ii).Image ) - nFG(ii); % nBG = tot number in BB minus num of FG
end 

答案 1 :(得分:1)

仅使用'BoundingBox'属性

z = regionprops( L, 'BoundingBox' );
nFG = zeros(1,numel(z)); % pre-allocate
nBG = zeros(1,numel(z));
for ii=1:numel(z), % in case there are more than one object in the image
    bb = imcrop( E, z(ii).BoundingBox ); % crop the mask according to BoundingBox
    nFG(ii) = nnz(bb); % count number of FG pixels
    nBG(ii) = numel( bb ) - nFG(ii); % nBG = tot number in BB minus num of FG
end