【数字图像处理】阈值处理

图像阈值处理是实现图像分割的一种方法,常用的阈值分割方法有简单阈值,自适应阈值,Otsu's二值化等。

cv2.threshold()可以用来进行图像阈值处理,cv2.threshold(src, thresh, maxval, type) 第一个参数是原图像,第二个参数是对像素值进行分类的阈值,第三个参数是当像素值高于(小于)阈值时,应该被赋予的新的像素值,第四个参数是阈值方法。函数有两个返回值,一个为retVal, 一个阈值化处理之后的图像。

常用的阈值方法有:

全局阈值:

 

自适应阈值

当同一幅图像不同部分具有不同的亮度时,全局阈值并不适用,此时我们会采用自适应阈值,自适应阈值会在图像上每一个小区域计算与其对应的阈值。可以使用cv2.adaptiveThreshold()要传入三个参数:阈值计算方法,邻域大小,常数C, 阈值等于平均值或者加权平均值减去这个常数。

import numpy as np
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('/home/vincent/Pictures/work/uy_gnix_iac.jpg')

ret, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
ret, thresh2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
ret, thresh3 = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC)
ret, thresh4 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO)
ret, thresh5 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV)

images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]


for i in range(6):
	plt.subplot(2,3, i+1)
	plt.imshow(images[i])
plt.suptitle('fixed threshold')

img = cv2.imread('/home/vincent/Pictures/work/barbara.png', 0)

print(img.shape)

thresh6 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)

thresh7 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)

ret, thresh8 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

images2 = [img, thresh6, thresh7, thresh8]


plt.figure(2)
for i in range(4):
	plt.subplot(1,4,i+1)
	plt.imshow(images2[i],'gray')
plt.suptitle('adaptive threshold')

plt.show()

 

 

posted @ 2018-07-04 20:57  VincentCheng  阅读(7619)  评论(0编辑  收藏  举报