MATLAB中二值图像的直方图

问题描述 投票:0回答:2

我正在尝试做二进制图像的垂直直方图。我不想使用MATLAB的功能。怎么做?

我试过这段代码,但我不知道它是否正确:

function H = histogram_binary(image)
[m,n] = size(image);
H = zeros(1,256);
for i = 1:m
    for j = 1:n
        H(1,image(i,j)) = H(1,image(i,j))+1;
    end
end

图像是:

The picture

结果:

vertical histogram

为什么我不能在直方图中看到黑色像素的值?

matlab image-processing histogram
2个回答
1
投票
% Read the binary image...
img = imread('66He7.png');

% Count total, white and black pixels...
img_vec = img(:);
total = numel(img_vec);
white = sum(img_vec);
black = total - white;

% Plot the result in the form of an histogram...
bar([black white]);
set(gca(),'XTickLabel',{'Black' 'White'});
set(gca(),'YLim',[0 total]);

输出:

BW Histogram

对于你的代码有什么问题,它不计算黑色像素,因为它们的值为0,你的循环从1开始...重写如下:

function H = histogram_binary(img)
    img_vec = img(:);
    H = zeros(1,256);

    for i = 0:255
        H(i+1) = sum(img_vec == i);
    end
end

但请记住,计算二进制图像上的所有字节出现次数(只能包含01值)是有点无意义的,会使您的直方图缺乏可读性。另外,请避免使用image作为变量名,因为这会覆盖an existing function


0
投票

如上面评论中的@beaker所述,在这种情况下,垂直直方图通常是指垂直投影。这是一种方法:

I = imread('YcP1o.png'); % Read input image
I1 = rgb2gray(I); % convert image to grayscale
I2 = im2bw(I1); % convert grayscale to binary
I3 = ~I2; % invert the binary image
I4 = sum(I3,1); % project the inverted binary image vertically
I5 = (I4>1); % ceil the vector 
plot([1:1:size(I,2)],I5); ylim([0 2])

您可以进一步检查0->1过渡以使用sum(diff(I5)>0)计算字符数,在这种情况下,13作为答案。

© www.soinside.com 2019 - 2024. All rights reserved.