基本概念:图像阈值一般用于图像阈值分割,图像阈值即图像分割的基准,一般对象为灰度图像,基于此可完成图像的二值化。
opencv中提供了不同的阈值准则,以python操作opencv为例:
ret, dst = cv2.threshold(src, thresh, maxval, type)
另外,type值还有两个选择,为自适应阈值算法,不是固定阈值,此时传入参数thresh不会起作用。
cv2.THRESH_OTSU 使用大津法选择最优的thresh;
cv2.THRESH_TRIANGLE 使用三角法确定thresh;
下面看看不同阈值分割准则的效果:
代码:
import cv2 #opencv读取的格式是BGR
import numpy as np
import matplotlib.pyplot as plt#Matplotlib是RGB
%matplotlib inline
img=cv2.imread('cat.jpg')
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh1 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
ret, thresh2 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV)
ret, thresh3 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TRUNC)
ret, thresh4 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO)
ret, thresh5 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO_INV)
ret, thresh6 = cv2.threshold(img_gray, 0, 255, cv2.THRESH_OTSU)
ret, thresh7 = cv2.threshold(img_gray, 0, 255, cv2.THRESH_TRIANGLE)
titles = ['Original Image', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV', 'OTSU', 'TRIANGLE']
images = [img, thresh1, thresh2, thresh3, thresh4, thresh5, thresh6, thresh7]
for i in range(8):
plt.subplot(2, 4, i + 1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show()