已阅: 129
目的
原理
- 求灰度直方图
- 根据灰度直方图,将灰度直方图分割,以数量处于中间的灰度值作为阈值(但因为图像不是双峰灰度直方图,因此是取了前20%)。
- 设置大小与灰度图大小一致的二值数组,其中,灰度图像素的灰度值大于阈值,则数组对应位置为1,否则为0.
- 将数组与灰度图相乘,可以得到一个像素灰度值只在0或(阈值, 255)间的图像,即分割后的图像。
实验结果
代码
clear all;
ima = imread('2.jpg');
grayIma = rgb2gray(ima);
[height, width] = size(grayIma);
histArray = zeros(1, 256);
array = zeros(height, width);
for row = 1:1:height
for col = 1:1:width
temp = grayIma(row, col) + 1;
histArray(1, temp) = histArray(1, temp) + 1;
end
end
mid = sum(histArray)/5;
sum = 0;
for pos = 1:1:256
sum = sum + histArray(1,pos);
if(sum > mid)
divisionValue = pos;
break;
end
end
for row = 1:1:height
for col = 1:1:width
if(grayIma(row, col) < divisionValue)
array(row, col) = 0;
else
array(row, col) = 1;
end
end
end
subplot(2,2,1);
imshow(grayIma);
subplot(2,2,3);
bar(histArray);
grayIma2Division = grayIma;
for row = 1:1:height
for col = 1:1:width
grayIma2Division(row, col) = grayIma(row, col) * array(row, col);
end
end
subplot(2,2,2);
imshow(grayIma2Division);
subplot(2,2,4);
imhist(grayIma2Division);
共有 0 条评论