在Opencv中,cv2.threshold
函数用于对图像进行阈值处理,将图像的像素值转换为二进制形式。其用法如下:
retval, thresholded_img = cv2.threshold(src, thresh, maxval, type)
参数说明:
src
:输入的图像thresh
:阈值maxval
:当像素值超过阈值时赋予的值type
:阈值处理的类型,包括:
cv2.THRESH_BINARY
:超过阈值的像素赋予maxval
,否则赋予0cv2.THRESH_BINARY_INV
:超过阈值的像素赋予0,否则赋予maxval
cv2.THRESH_TRUNC
:超过阈值的像素保持不变,否则赋予阈值cv2.THRESH_TOZERO
:超过阈值的像素保持不变,否则赋予0cv2.THRESH_TOZERO_INV
:超过阈值的像素赋予0,否则保持不变函数返回值:
retval
:实际使用的阈值thresholded_img
:处理后的二值化图像示例代码:
import cv2
img = cv2.imread('image.jpg', 0) # 以灰度模式读取图像
retval, thresholded_img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
cv2.imshow('Thresholded Image', thresholded_img)
cv2.waitKey(0)
cv2.destroyAllWindows()