MATLABR2018b代码,对灰度图像进行OSTU二值化
时间: 2024-04-30 18:20:55 浏览: 107
灰度图像二值化代码
以下是MATLAB R2018b代码,可用于对灰度图像进行OSTU二值化:
```matlab
% 读入灰度图像
I = imread('image.jpg');
% 计算灰度图像的直方图
counts = imhist(I);
% 计算灰度图像的像素总数
totalPixels = numel(I);
% 初始化最大方差和最佳阈值
maxVariance = 0;
bestThreshold = 0;
% 遍历灰度级,找到最佳阈值
for threshold = 0:255
% 计算前景像素数、背景像素数、前景像素平均灰度、背景像素平均灰度
foregroundPixels = sum(counts(threshold+1:256));
backgroundPixels = totalPixels - foregroundPixels;
foregroundMean = sum((threshold+1:256).*counts(threshold+1:256)) / foregroundPixels;
backgroundMean = sum((0:threshold).*counts(1:threshold+1)) / backgroundPixels;
% 计算类间方差
variance = foregroundPixels*backgroundPixels*(foregroundMean-backgroundMean)^2;
% 更新最大方差和最佳阈值
if variance > maxVariance
maxVariance = variance;
bestThreshold = threshold;
end
end
% 对灰度图像进行二值化
binaryImage = imbinarize(I, bestThreshold/255);
% 显示结果
imshow(binaryImage);
```
请将代码中的`image.jpg`替换为您要处理的图像文件名。
阅读全文