当图像各局部亮度不同时,全局阈值就很难将背景和目标分割。因此提出了自适应阈值,即在图像的不同区域采用不同的阈值进行分割。利用函数cv2.adaptiveThreshold()进行分割。
cv2.adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C)
参数:
1. src:原图像
2. maxValue:当阈值类型(thresholdType)采用cv2.THRESH_BINARY和cv2.THRESH_BINARY_INV时像素点被赋予的新值
3. adaptiveMethod:自适应阈值的计算方法,包括两种:
4. thresholdType:阈值分割类型,共5种,同cv2.threshold()的阈值分割类型参数,详情见https://blog.csdn.net/weixin_42216109/article/details/89553383
5. blockSize:用来计算阈值的邻域大小
6. C:常数,adaptiveMethod方法计算出的数值减去这个常数C就为阈值
返回值:
1. 阈值分割后的图像
e.g.
通过如下代码对比全局阈值分割和自适应阈值分割的区别
import cv2
import matplotlib.pyplot as plt
#载入原图
img_original=cv2.imread('E:\ShannonT\\notebook workspace\\images\\4.26.6.jpg',0)
#全局阈值分割
retval,img_global=cv2.threshold(img_original,130,255,cv2.THRESH_BINARY)
#自适应阈值分割
img_ada_mean=cv2.adaptiveThreshold(img_original,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,15,3)
img_ada_gaussian=cv2.adaptiveThreshold(img_original,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,15,3)
imgs=[img_original,img_global,img_ada_mean,img_ada_gaussian]
titles=['Original Image','Global Thresholding(130)','Adaptive Mean','Adaptive Guassian',]
#显示图片
for i in range(4):
plt.subplot(2,2,i+1)
plt.imshow(imgs[i],'gray')
plt.title(titles[i])
plt.xticks([])
plt.yticks([])
plt.show()
结果显示如下:
补充:从自适应阈值分割的结果来看,图像中存在较多的噪声,于是我们可以先通过函数cv2.GaussianBlur()进行噪声去除,详情参考https://blog.csdn.net/duwangthefirst/article/details/79971338
import cv2
import matplotlib.pyplot as plt
#载入原图
img_original=cv2.imread('E:\ShannonT\\notebook workspace\\images\\4.26.6.jpg',0)
#高斯滤波
img_blur=cv2.GaussianBlur(img_original,(5,5),5)
#自适应阈值分割
img_thresh=cv2.adaptiveThreshold(img_original,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,15,3)
img_thresh_blur=cv2.adaptiveThreshold(img_blur,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,15,3)
#显示图像
imgs=[img_thresh,img_thresh_blur]
titles=['img_thresh','img_thresh_blur']
for i in range(2):
plt.subplot(1,2,i+1)
plt.imshow(imgs[i],'gray')
plt.title(titles[i])
plt.xticks([])
plt.yticks([])
plt.show()
结果如下所示,可以发现噪声数量明显减少。