首先导入库

1
2
import cv2 as cv
import numpy as np

注意,最常见的阈值图片就是二维码。

1
#本讲来看阈值,可以用来颠倒二维码噢!

查看两张图片,有颜色读取

1
2
img1 = cv.imread("def.jpg", cv.IMREAD_COLOR)
img2 = cv.imread("abc.jpg", cv.IMREAD_COLOR)

导入画图包,这个包在以后会非常常用

1
2
#再来引入一下画图的包
import matplotlib.pyplot as plt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
ret, thresh1 = cv.threshold(img1, 127, 255, cv.THRESH_BINARY)#只要大于127就设置为255,小于127设置为0,白变黑,黑变白
ret, thresh2 = cv.threshold(img1, 127, 255, cv.THRESH_BINARY_INV)#反过来,小于127设置为0,大于127设置为255
ret, thresh3 = cv.threshold(img1, 127, 255, cv.THRESH_TRUNC)#大于阈值设置为最大,否则不变
ret, thresh4 = cv.threshold(img1, 127, 255, cv.THRESH_TOZERO)#大于阈值不变,否则设置为0
ret, thresh5 = cv.threshold(img1, 127, 255, cv.THRESH_TOZERO_INV)#小于阈值不变,大于阈值为0,也就是原来最亮的地方变黑,原来变黑的地方不变。


titles = ["Original image", "BINARY", "BINARY_INV", "TRUNC", "TOZERO", "TOZERO_INV"]

imgs = [img1, thresh1, thresh2, thresh3, thresh4, thresh5]

for i in range(6):
plt.subplot(2, 3, i + 1), plt.imshow(imgs[i], "gray")
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show()
#效果如下:

image-20231016145325679