Otsu分割算法代码
时间: 2023-07-03 17:13:52 浏览: 91
以下是Python实现的Otsu分割算法代码:
```python
import numpy as np
import cv2
def otsu_threshold(img):
# 计算图像直方图
hist, bins = np.histogram(img.ravel(), 256, [0,256])
# 归一化直方图
hist_norm = hist.astype('float32') / img.size
# 初始化类间方差和最大值
inter_class_var = np.zeros(256)
max_var = 0
# 计算类间方差
for threshold in range(256):
# 计算前景和背景的像素点数和权重
w0 = sum(hist_norm[:threshold])
w1 = 1 - w0
if w0 == 0 or w1 == 0:
continue
mean0 = sum(np.arange(threshold) * hist_norm[:threshold]) / w0
mean1 = sum(np.arange(threshold, 256) * hist_norm[threshold:]) / w1
inter_class_var[threshold] = w0 * w1 * (mean0 - mean1) ** 2
# 记录最大类间方差和最优阈值
if inter_class_var[threshold] > max_var:
max_var = inter_class_var[threshold]
threshold_optimal = threshold
# 返回最优阈值
return threshold_optimal
# 读取图像
img = cv2.imread('image.jpg', 0)
# Otsu分割
threshold = otsu_threshold(img)
print('Optimal threshold:', threshold)
# 二值化
img_binary = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY)[1]
# 显示图像
cv2.imshow('Original Image', img)
cv2.imshow('Binary Image', img_binary)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,`otsu_threshold`函数实现了Otsu分割算法,输入为灰度图像,输出为最优阈值。`cv2.threshold`函数实现了二值化操作,根据最优阈值将图像分成黑白两部分。
阅读全文