MATLABR2018b代码,对灰度图像进行OSTU二值化
时间: 2024-05-13 22:18:25 浏览: 81
以下是MATLAB R2018b代码,用于对灰度图像进行OSTU二值化:
```matlab
% 读入灰度图像
grayImg = imread('lena_gray.jpg');
% 计算灰度直方图
histogram = imhist(grayImg);
% 计算总像素数
totalPixels = sum(histogram);
% 初始化类间方差和最大值
maxVariance = 0;
optimalThreshold = 0;
% 遍历所有可能的阈值
for threshold = 1:255
% 计算两个类的像素数和权重
class1Pixels = sum(histogram(1:threshold));
class2Pixels = totalPixels - class1Pixels;
class1Weight = class1Pixels / totalPixels;
class2Weight = class2Pixels / totalPixels;
% 计算两个类的平均灰度值
class1Mean = sum((0:threshold-1) .* histogram(1:threshold)) / class1Pixels;
class2Mean = sum(threshold:255 .* histogram(threshold+1:end)) / class2Pixels;
% 计算类间方差
variance = class1Weight * class2Weight * (class1Mean - class2Mean)^2;
% 更新最大类间方差和最优阈值
if variance > maxVariance
maxVariance = variance;
optimalThreshold = threshold;
end
end
% 对图像进行二值化
binaryImg = grayImg > optimalThreshold;
% 显示结果
subplot(1,2,1), imshow(grayImg), title('原图');
subplot(1,2,2), imshow(binaryImg), title('OSTU二值化');
```
在上面的代码中,我们首先使用 `imread` 函数读入灰度图像。然后,我们计算灰度直方图并计算总像素数。接下来,我们遍历所有可能的阈值,并计算两个类的像素数、权重和平均灰度值。然后,我们根据公式计算类间方差,并更新最大类间方差和最优阈值。最后,我们使用 `>` 运算符将图像二值化,并使用 `imshow` 函数显示原图和OSTU二值化结果。
阅读全文
相关推荐
















