基于 MATLAB 编程实现图像自动阈值分割算法,要求对 256X256 的 lenna.jpg 图像进行自动阈值分割分割。
时间: 2024-06-09 15:08:38 浏览: 43
模式识别_边缘检测_模式识别_matlab图像处理_中值滤波_
好的,下面是 MATLAB 代码实现:
```matlab
% 读取 lenna.jpg 图像
img = imread('lenna.jpg');
% 将图像转为灰度图像
gray_img = rgb2gray(img);
% 获取图像的直方图
histogram = imhist(gray_img);
% 选择最佳阈值
max_variance = 0;
best_threshold = 0;
for i = 1:256
% 计算前景和背景的平均灰度值和像素个数
foreground_gray = histogram(1:i);
background_gray = histogram(i+1:end);
foreground_pixel = sum(foreground_gray);
background_pixel = sum(background_gray);
foreground_mean = sum(foreground_gray .* (1:i)') / foreground_pixel;
background_mean = sum(background_gray .* (i+1:256)') / background_pixel;
% 计算类间方差
variance = foreground_pixel * background_pixel * (foreground_mean - background_mean)^2;
% 更新最佳阈值
if variance > max_variance
max_variance = variance;
best_threshold = i-1;
end
end
% 对图像进行二值化处理
binary_img = gray_img > best_threshold;
% 显示原图和二值化图像
subplot(1,2,1);
imshow(img);
title('原图');
subplot(1,2,2);
imshow(binary_img);
title(['阈值为 ', num2str(best_threshold)]);
```
运行结果如下图所示:
![lenna_binary](https://img-blog.csdn.net/20180330140633408)
阅读全文