全局阈值分割——直方图法函数返回图片
时间: 2023-10-06 18:10:21 浏览: 92
matlab图像专题:47 直方图阈值法进行图像分割.zip
以下是一个使用全局阈值分割(直方图法)的函数,它将返回阈值处理后的二值图像:
```python
import cv2
import numpy as np
def global_thresholding(image):
# 将图像转换为灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 计算图像直方图
hist = cv2.calcHist([gray],[0],None,[256],[0,256])
# 计算总像素数
total_pixels = gray.shape[0] * gray.shape[1]
# 计算每个像素值出现的概率
probabilities = hist / total_pixels
# 计算累积分布函数
cdf = np.cumsum(probabilities)
# 找到最小阈值
min_threshold = 0
min_value = float('inf')
for i in range(1, 256):
w0 = cdf[i]
w1 = 1 - w0
if w0 == 0 or w1 == 0:
continue
mu0 = np.sum(probabilities[:i] * np.arange(i)) / w0
mu1 = np.sum(probabilities[i:] * np.arange(i, 256)) / w1
value = w0 * w1 * (mu0 - mu1) ** 2
if value < min_value:
min_threshold = i
min_value = value
# 应用阈值
ret, thresh = cv2.threshold(gray, min_threshold, 255, cv2.THRESH_BINARY)
return thresh
```
使用方法:
```python
# 读取图像文件
image = cv2.imread('image.jpg')
# 应用全局阈值分割
thresh = global_thresholding(image)
# 显示结果图像
cv2.imshow('Thresholded Image', thresh)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文