编写matlab对lena图像实现Otsu自动阈值分割,得到二值化的图像(不允许使用库函数中的自适应阈值分函数)。
时间: 2024-11-25 16:18:59 浏览: 32
在MATLAB中,Otsu自动阈值分割是一种无参数的图像二值化技术,它基于两个最大类间方差的原则来确定最佳阈值。以下是手动实现Otsu算法对Lena图像进行二值化的步骤:
1. 加载Lena图像:
```matlab
img = imread('lena.jpg'); % 替换为你的 Lena 图像路径
```
2. 归一化图像(如果需要):
```matlab
img = im2double(img); % 转换为0-1范围内的灰度图像
```
3. 计算直方图及其累积分布函数 (CDF):
```matlab
histogram = histcounts(double(img(:)), 256); % 将图像展平并计算直方图
cdf = cumsum(histogram) / sum(histogram);
```
4. 初始化变量:
```matlab
w1 = zeros(size(cdf)); % 类别1像素权重
w2 = cdf; % 类别2像素权重(等于剩余像素权重)
mu1 = []; % 第一类像素平均灰度值
mu2 = []; % 第二类像素平均灰度值
sigma1 = 0; % 第一类像素方差
sigma2 = 0; % 第二类像素方差
best_threshold = 0;
best_bisect = Inf; % 最佳双类划分点
```
5. Otsu算法的核心部分(迭代过程):
```matlab
for i = 1:length(cdf)-1
w1(i) = cdf(i); % 当前类别1像素权重
w2(length(cdf) - i) = w2(i); % 更新类别2权重
mu1 = sum(histogram(1:i).*double(0:i)) / w1(i); % 计算均值
mu2 = sum(histogram(i+1:end).*double(i+1:length(cdf))) / w2(i); % 计算均值
sigma1 = w1(i) * (mu1.^2); % 计算方差
sigma2 = w2(i) * (mu2.^2); % 计算方差
% 计算Bisecting Method(双类划分点)
bisect = (i + (i + 1)) / 2;
% 计算类间方差
inter_class_variance = w1(i) * w2(i) * (mu1 - mu2).^2;
if inter_class_variance < best_bisect && (w1(i) > 0 && w2(i) > 0)
best_bisect = inter_class_variance;
best_threshold = double(bisect);
end
end
```
6. 根据找到的最佳阈值生成二值图像:
```matlab
binary_img = img > best_threshold; % 二值化
```
阅读全文
相关推荐


















