OpenCV阈值
3.1阈值
代码:
import cv2 from matplotlib import pyplot as plt # 读取图像 img1 = cv2.imread("./image/card10.png") # 检查图像是否成功加载 if img1 is None: print("Error: Image not found or unable to read.") exit() # 转换为灰度图 gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) # 应用不同的阈值操作 _, th1 = cv2.threshold(gray, 99, 255, cv2.THRESH_BINARY) _, th2 = cv2.threshold(gray, 99, 255, cv2.THRESH_BINARY_INV) _, th3 = cv2.threshold(gray, 99, 255, cv2.THRESH_TRUNC) _, th4 = cv2.threshold(gray, 99, 255, cv2.THRESH_TOZERO) _, th5 = cv2.threshold(gray, 99, 255, cv2.THRESH_TOZERO_INV) # 设置标题列表(注意拼写错误:应该是 "original") titles = ["Original", "TH_BINARY", "TH_BINARY_INV", "TH_TRUNC", "TH_TOZERO", "TH_TOZERO_INV"] images = [img1, th1, th2, th3, th4, th5] # 使用matplotlib显示图像 for i in range(6): plt.subplot(2, 3, i + 1) plt.imshow(images[i], cmap='gray') # 使用cmap='gray'来指定灰度颜色映射 plt.title(titles[i]) plt.axis('off') # 关闭坐标轴 plt.tight_layout() # 调整子图参数以防止重叠 plt.show()
_, th1 = cv2.threshold(gray, 99, 255, cv2.THRESH_BINARY)
:对灰度图像gray
进行二值化阈值操作。99
是阈值,255
是最大值,cv2.THRESH_BINARY
表示二值化阈值类型。大于阈值的像素设置为最大值255
(白色),小于等于阈值的像素设置为0
(黑色),结果存储在th1
中。_, th2 = cv2.threshold(gray, 99, 255, cv2.THRESH_BINARY_INV)
:进行反二值化阈值操作。与THRESH_BINARY
相反,大于阈值的像素设置为0
,小于等于阈值的像素设置为255
,结果存储在th2
中。_, th3 = cv2.threshold(gray, 99, 255, cv2.THRESH_TRUNC)
:截断阈值操作。大于阈值的像素设置为阈值99
,小于等于阈值的像素保持不变,结果存储在th3
中。_, th4 = cv2.threshold(gray, 99, 255, cv2.THRESH_TOZERO)
:阈值化为 0 操作。大于阈值的像素保持不变,小于等于阈值的像素设置为0
,结果存储在th4
中。_, th5 = cv2.threshold(gray, 99, 255, cv2.THRESH_TOZERO_INV)
:反阈值化为 0 操作。大于阈值的像素设置为0
,小于等于阈值的像素保持不变,结果存储在th5
中。