ret, dst = cv2.threshold(src, thresh, maxval, type)
- ret : 判断二值化是否成功 布尔类
- dst : 二值化后输出的图像
- src : 输入图像,只能是单通道图像,一般灰度图像
- thresh : 设定的阈值
- maxval : 如果超过阈值会被设置为maxvam,一般为255(逻辑1),当像素值超过了阈值(或者小于阈值,根据type来决定),所赋予的值。
- type : 二值化操作类型,一共分为五种
- - cv2.THRESH_BINARY 超过阈值部分取maxval(最大值),否则取0
- - cv2.THRESH_BINARY_INV THRESH_BINARY的反转
- - cv2.THRESH_TRUNC 大于阈值部分设为阈值,否则不变
- - cv2.THRESH_TOZERO 大于阈值部分不改变,否则设为0
- - cv2.THRESH_TOZERO_INV THRESH_TOZERO的反转
import cv2 #opencv读取的格式是BGR
import numpy as np
import matplotlib.pyplot as plt#Matplotlib是RGB
%matplotlib inline
img=cv2.imread('lena.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)
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), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show()