簡體   English   中英

MATLAB中二進制圖像的直方圖

[英]Histogram of binary image in MATLAB

我試圖做一個二進制圖像的垂直直方圖。 我不想使用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

該圖像是:

圖片

結果:

垂直直方圖

為什么在直方圖中看不到黑色像素的值?

% 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]);

輸出:

體重直方圖

對於您的代碼而言,它不計算黑色像素,因為它們的值為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作為變量名,因為這會覆蓋現有函數

如@ 燒杯在上面的評論中提到的,在這種情況下,垂直直方圖通常是指垂直投影。 這是一種方法:

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])

您可以使用sum(diff(I5)>0)進一步檢查0->1轉換以計算字符數,在這種情況下,其結果為13

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM