标签:[] size src tar 分享图片 color UNC gradient 参数
import cv2 import matplotlib.pyplot as plt
# 灰度图读入 img = cv2.imread(‘gradient.jpg‘, 0) # 阈值分割 ret, th = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) cv2.imshow(‘thresh‘, th) cv2.waitKey(0)
cv2.threshold()用来实现阈值分割,有4个参数:
理解这5种阈值方式:
# 应用5种不同的阈值方法 ret, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) ret, th2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV) ret, th3 = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC) ret, th4 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO) ret, th5 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV) titles = [‘Original‘, ‘BINARY‘, ‘BINARY_INV‘, ‘TRUNC‘, ‘TOZERO‘, ‘TOZERO_INV‘] images = [img, th1, th2, th3, th4, th5] # 使用Matplotlib显示 # 两行三列图 for i in range(6): plt.subplot(2, 3, i + 1) plt.imshow(images[i], ‘gray‘) plt.title(titles[i], fontsize=8) plt.xticks([]), plt.yticks([]) # 隐藏坐标轴 plt.show()
固定阈值将整幅图片分成两类值,它并不适用于明暗分布不均的图片。而cv2.adaptiveThreshold()自适应阈值会每次取图片的一小部分计算阈值。这样图片不同区域的阈值就不尽相同。
# 自适应阈值对比固定阈值 img = cv2.imread(‘sudoku.jpg‘, 0) # 固定阈值 ret, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) # 自适应阈值 th2 = cv2.adaptiveThreshold( img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 4) th3 = cv2.adaptiveThreshold( img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 17, 6) titles = [‘Original‘, ‘Global(v = 127)‘, ‘Adaptive Mean‘, ‘Adaptve Gaussian‘] images = [img, th1, th2, th3] for i in range(4): plt.subplot(2, 2, i + 1), plt.imshow(images[i], ‘gray‘) plt.title(titles[i], fontsize=8) plt.xticks([]), plt.yticks([]) # 隐藏坐标轴 plt.show()
cv2.adaptiveThreshold()的5个参数:
ADAPTIVE_THRESH_MEAN_C:小区域内取均值
ADAPTIVE_THRESH_GAUSSIAN_C:小区域内加权求和,权重是高斯核
OpenCV-Python基础教程5-阈值分割与Otsu阈值法
标签:[] size src tar 分享图片 color UNC gradient 参数
原文地址:https://www.cnblogs.com/gezhuangzhuang/p/10292389.html