import cv2
import numpy as np
# Gray scale
def BGR2GRAY(img):
b = img[:, :, 0].copy()
g = img[:, :, 1].copy()
r = img[:, :, 2].copy()
# Gray scale
out = 0.2126 * r + 0.7152 * g + 0.0722 * #bgr转灰度图像
out = out.astype(np.uint8)#八位整型灰度
return out
# Otsu Binarization
def otsu_binarization(img, th=128):
max_sigma = 0
max_t = 0
# determine threshold
for _t in range(1, 255):
v0 = out[np.where(out < _t)]#out里面小于_t的灰度值存到v0里,这是前景像素的处理
m0 = np.mean(v0) if len(v0) > 0 else 0.#对v0求均值也就是求平均灰度m0
w0 = len(v0) / (H * W)#某像素所占整个图像像素比例
v1 = out[np.where(out >= _t)]#同理,这个是背景元素处理
m1 = np.mean(v1) if len(v1) > 0 else 0.
w1 = len(v1) / (H * W)
sigma = w0 * w1 * ((m0 - m1) ** 2)#一个特定公式
if sigma > max_sigma:
max_sigma = sigma#得到最大的sigma
max_t = _t#得到最大的t
# Binarization
print("threshold >>", max_t)
th = max_t
out[out < th] = 0
out[out >= th] = 255
return out
# Read image
img = cv2.imread("imori.jpg").astype(np.float32)
H, W, C =img.shape
# Grayscale
out = BGR2GRAY(img)
# Otsu's binarization
out = otsu_binarization(out)
# Save result
cv2.imwrite("out.jpg", out)
cv2.imshow("result", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
图像处理100问-大津法-otsu全局自适应阈值分割
最新推荐文章于 2023-12-06 17:43:00 发布