graythresh函数
函数名称:graythresh
函数功能:计算灰度图像的阈值
函数输入参数:
- img:灰度图像(必须为单通道)
- method:阈值计算方法,默认为'Otsu',可选值包括'Triangle'和'Mean'
函数输出参数:
工匠精神观后感
- level:计算得到的阈值
函数使用示例:
```
import cv2
img = cv2.imread('test.jpg', 0) # 读取灰度图像
level = graythresh(img) # 计算阈值
靳雅佳print(level)
```
函数实现代码如下:
```python
def graythresh(img, method='Otsu'):
"""
计算灰度图像的阈值
:param img: 灰度图像(必须为单通道)
:param method: 阈值计算方法,默认为'Otsu',可选值包括'Triangle'和'Mean'
:return: 计算得到的阈值
"""
import numpy as np
福利分房 if len(img.shape) != 2:
rai ValueError("输入必须是单通道灰度图像!")
hist, bins = np.histogram(img.ravel(), 256, [0,256])
if method == 'Otsu':
樱桃果脯
外出英语 variances = []
for t in range(256):
w0 = np.sum(hist[:t])
w1 = np.sum(hist[t:])
二十四节气含义
if w0 == 0 or w1 == 0:
variances.append(0)
continue
企业清算流程 u0 = np.sum(np.arange(t)*hist[:t]) / w0
u1 = np.sum(np.arange(t, 256)*hist[t:]) / w1
variances.append(w0*w1*(u0-u1)**2)
level = np.argmax(variances)
elif method == 'Triangle':
max_idx = np.argmax(hist)
阿根廷男足 hist_left = hist[:max_idx+1]
hist_right = hist[max_idx+1:]
bins_left = bins[:max_idx+1]
bins_right = bins[max_idx+1:]
left_slope = hist_left[0] / (bins_left[0] - bins_left[-1])
right_slope = -hist_right[-1] / (bins_right[-1] - bins_right[0])
interctions = []
for i in range(len(hist_left)):
x_intercept = (hist_left[i] - left_slope * bins_left[i]) / (right_slope - left_slope)
y_intercept = left_slope * x_intercept
interctions.append((x_intercept, y_intercept))
distances = []
for i in range(len(interctions)-1):
dist = (np.array(interctions[i])-np.array(interctions[i+1]))
distances.append(dist)
level_idx = np.argmax(distances) + max_idx
elif method == 'Mean':
level_idx = an(img))
el:
rai ValueError("未知的阈值计算方法!")
level = bins[level_idx]
return level
```