编写程序,实现 OTSU 阈值分割算法
时间: 2023-09-03 09:15:10 浏览: 140
以下是Python实现OTSU阈值分割算法的代码:
```python
import cv2
import numpy as np
def otsu_threshold(img):
"""
OTSU阈值分割算法
:param img: 灰度图像
:return: 二值图像
"""
# 统计像素值的个数
pixel_counts = [np.sum(img == i) for i in range(256)]
# 图像像素总数
total_pixels = img.shape[0] * img.shape[1]
# 计算每个像素值的概率
pixel_probs = [pixel_count / total_pixels for pixel_count in pixel_counts]
# 计算每个灰度级的均值
mean_values = [i * pixel_probs[i] for i in range(256)]
# 计算全局均值
global_mean = np.sum(mean_values)
# 初始化类间方差和最佳阈值
max_variance, best_threshold = 0, 0
# 遍历所有可能的阈值
for threshold in range(256):
# 计算前景像素的概率和均值
foreground_probs = np.sum(pixel_probs[:threshold])
foreground_mean = np.sum(mean_values[:threshold]) / foreground_probs
# 计算背景像素的概率和均值
background_probs = np.sum(pixel_probs[threshold:])
background_mean = np.sum(mean_values[threshold:]) / background_probs
# 计算类间方差
variance = foreground_probs * background_probs * (foreground_mean - background_mean) ** 2
# 更新最大类间方差和最佳阈值
if variance > max_variance:
max_variance = variance
best_threshold = threshold
# 二值化图像
thresholded_img = np.zeros(img.shape, dtype=np.uint8)
thresholded_img[img > best_threshold] = 255
return thresholded_img
```
使用示例:
```python
# 读取原始图像
img = cv2.imread('lena.png', cv2.IMREAD_GRAYSCALE)
# 使用OTSU阈值分割算法得到二值图像
thresholded_img = otsu_threshold(img)
# 显示二值图像
cv2.imshow('OTSU Threshold', thresholded_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
需要注意的是,该算法适用于单峰图像,对于多峰图像需要进行预处理,如使用直方图等方法将其转化为单峰图像再进行阈值分割。
阅读全文