MATLAB代码,对灰度图像进行OSTU二值化
时间: 2024-05-16 22:17:50 浏览: 98
以下是MATLAB代码,对灰度图像进行OSTU二值化:
```matlab
% 读取灰度图像
img = imread('gray_image.png');
% 计算图像的直方图
histogram = imhist(img);
% 获取图像像素总数
total_pixels = numel(img);
% 初始化最优阈值和最大类间方差
optimal_threshold = 0;
max_variance = 0;
% 对每个灰度级别进行遍历,计算每个灰度级别作为阈值时的类间方差
for threshold = 1:255
% 计算前景和背景像素的数量
foreground_pixels = sum(histogram(threshold+1:256));
background_pixels = sum(histogram(1:threshold));
% 计算前景和背景像素的概率
foreground_probability = foreground_pixels / total_pixels;
background_probability = background_pixels / total_pixels;
% 计算前景和背景像素的平均灰度值
foreground_mean = sum((threshold+1:256) .* histogram(threshold+1:256)) / foreground_pixels;
background_mean = sum((1:threshold) .* histogram(1:threshold)) / background_pixels;
% 计算类间方差
variance = foreground_probability * background_probability * (foreground_mean - background_mean)^2;
% 更新最优阈值和最大类间方差
if variance > max_variance
max_variance = variance;
optimal_threshold = threshold;
end
end
% 二值化图像
binary_img = imbinarize(img, optimal_threshold/255);
% 显示原始图像和二值化图像
figure;
subplot(1,2,1);
imshow(img);
title('Original Image');
subplot(1,2,2);
imshow(binary_img);
title('OSTU Binarized Image');
```
阅读全文