adaptiveThreshold
参数
InputArray src
OutputArray dst
double maxValue
int adaptiveMethod,
int thresholdType
int blockSize
double C
原理
为每个像素计算阈值,并二值化(参数thresholdType是二值化类型,参数maxValue是二值化的大灰度值)。
计算阈值有两种方法(参数adaptiveMethod),一是取该像素邻域blockSize*blockSize块的灰度均值,一是根据高斯函数、按照周围像素距目标像素的距离进行加权计算。C是一个偏移值,可正可负。
适用场合
代码以及结果显示
import cv2
from matplotlib.pylab import plt
import numpy as np
# 为了支持plot的中文显示,加上这两句
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']
imgColor = cv2.imread("D:/test.jpg", cv2.IMREAD_COLOR)
img = cv2.cvtColor(imgColor, cv2.COLOR_RGB2GRAY)
dst = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 177, -4)
dst, contours, hierarchy = cv2.findContours(dst, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
size = dst.shape
tmp = np.ones((size[0], size[1], 3),np.uint8)*255
cv2.drawContours(tmp, contours, -1, (255, 0, 0), 3)
rect = cv2.boundingRect(contours[0])
fig = plt.figure(figsize=(15, 15))
plt.subplot(221)
plt.title("源图像", size=16)
plt.imshow(imgColor)
plt.subplot(222)
plt.title("灰度图", size=16)
plt.imshow(img, cmap='gray')
plt.subplot(223)
plt.title("自适应阈值结果", size=16)
plt.imshow(dst, cmap='gray')
plt.subplot(224)
plt.title("轮廓图", size=16)
plt.imshow(tmp, cmap='gray')
plt.show()
效果