使用自适应阈值处理图像
import cv2 as cv
from matplotlib import pyplot as plt
img = cv.imread('picture\\head_show.jpg', 0)
thresh1 = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 119, 5)
thresh2 = cv.adaptiveThreshold(img, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 119, 5)
titles = ['img', 'MEAN_C', 'GAUSSIAN_C']
images = [img, thresh1, thresh2]
for i in range(3):
plt.subplot(1, 3, i+1), plt.imshow(images[i]), plt.title(titles[i])
plt.show()
cv.adaptivThreshold()参数如下:
adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C[, dst]) -> dst
需要注意的是thresholdType里cv.THRESH_TRUNC的类型不支持,会报错。
同时blocSize为像素周围指定多少距离的区域,为3, 5, 9…等除1外的奇数,即满足blockSize % 2 == 1 && blockSize > 1
在全局阈值的方法cv.threshold中需要返回两个值ret、thresh
但在自适应阈值的方法cv.adaptiveThreshold中只返回一个值,加上ret会报错,同时输入图像需为灰度图像。