MATLAB实现改进Otsu算法的代码
1. 参数设置
% 读取图像
I = imread('example_image.jpg'); % 替换为实际图像路径
I = rgb2gray(I); % 转换为灰度图像
I = im2double(I); % 转换为双精度浮点数
2. 计算图像均值
% 计算图像均值
meanIntensity = mean(I(:));
3. 改进的Otsu算法
% 改进的Otsu算法
function threshold = improvedOtsu(I, meanIntensity)
% 获取图像大小
[rows, cols] = size(I);
% 初始化变量
totalPixels = rows * cols;
maxVariance = 0;
threshold = 0;
% 计算直方图
hist = imhist(I);
cumulativeHist = cumsum(hist);
% 计算全局均值
totalMean = sum((0:255) .* hist) / totalPixels;
% 在均值到最大灰度值之间搜索最佳阈值
for T = meanIntensity:255
% 计算前景和背景的像素数量
backgroundPixels = cumulativeHist(T);
foregroundPixels = totalPixels - backgroundPixels;
% 避免除以零
if backgroundPixels == 0 || foregroundPixels == 0
continue;
end
% 计算前景和背景的均值
backgroundMean = sum((0:T-1) .* hist(1:T)) / backgroundPixels;
foregroundMean = sum((T:255) .* hist(T+1:end)) / foregroundPixels;
% 计算类间方差
variance = backgroundPixels * foregroundPixels * (backgroundMean - foregroundMean)^2;
% 更新最大方差和阈值
if variance > maxVariance
maxVariance = variance;
threshold = T;
end
end
end
% 调用改进的Otsu算法
threshold = improvedOtsu(I, meanIntensity);
4. 图像分割
% 使用阈值进行图像分割
segmentedImage = I > threshold;
5. 显示结果
% 显示原始图像和分割后的图像
figure;
subplot(1, 2, 1);
imshow(I);
title('Original Image');
subplot(1, 2, 2);
imshow(segmentedImage);
title('Segmented Image');
参考代码 ostu图像分割阈值算法