图像的二值化就是将图像上的像素点的灰度值设置为0或255,这样将使整个图像呈现出明显的黑白效果。在数字图像处理中,二值图像占有非常重要的地位,图像的二值化使图像中数据量大为减少,从而能凸显出目标的轮廓。OpenCV中提供了函数cv::threshold();
如下图所示即为OpenCV中关于阈值的函数,其中:设置的阈值是针对每个像素点判断的,如果当前像素点的值大于阈值,赋什么值,maxval最大取值为255(0<黑>~255<白>)
简单使用:
import matplotlib.pyplot as plt
import cv2 as cv
img = cv.imread("images/girl.jpg", cv.IMREAD_COLOR)
image_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
ret, thresh1 = cv.threshold(image_gray, 127, 255, cv.THRESH_BINARY)
ret, thresh2 = cv.threshold(image_gray, 127, 255, cv.THRESH_BINARY_INV)
ret, thresh3 = cv.threshold(image_gray, 127, 255, cv.THRESH_TRUNC)
ret, thresh4 = cv.threshold(image_gray, 127, 255, cv.THRESH_TOZERO)
ret, thresh5 = cv.threshold(image_gray, 127, 255, cv.THRESH_TOZERO_INV)
titles = ['Original Image', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV']
images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]
for i in range(6):
plt.subplot(2, 3, i + 1)
if(i == 0):
plt.imshow(images[i])
plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show()