普通二值化
import cv2
def cv_show(neme, img):
# cv2.namedWindow(neme, cv2.WINDOW_NORMAL)
cv2.imshow(neme, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
img = cv2.imread('1.png')
# 灰度化
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 二值化
# 大于127=0,小于127=255
ret, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
# 大于127=255,小于127=0
ret, thresh2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
# 大于127=127,否则不变
ret, thresh3 = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC)
# 小于127=0,否则不变
ret, thresh4 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO)
# 大于127=0,否则不变
ret, thresh5 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV)
cv_show("s", img)
cv_show("s", thresh1)
cv_show("s", thresh2)
cv_show("s", thresh3)
cv_show("s", thresh4)
cv_show("s", thresh5)
自适应二值化
img = cv2.imread('1.png', 0)
# 中值滤波
img = cv2.medianBlur(img, 5)
ret, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
# 自适应阈值 二值化
# 11 为 Block size, 2 为 C 值
# cv2.ADPTIVE_THRESH_MEAN_C 阈值取自相邻区域的平均值
th2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
# v2.ADPTIVE_THRESH_GAUSSIAN_C:阈值取值相邻区域的加权和,权重为一个高斯窗口。
th3 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
cv_show("s", th2)
cv_show("s", th3)
Otsu’s 二值化
# Otsu’s 二值化
img = cv2.imread('1.png', 0)
# 两种写法
# 1、可以在后面加[1],代表直接返回第二个
# 2、直接接2个返回值
thresh, _ = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]
print(_)
print("="*100)
print(thresh1)
cv_show("s", _)
cv_show("s", thresh1)
调节阈值小工具(普通二值化) 有时候不靠谱,先自己用原本的方法验证一遍吧
import cv2
def nothing(x):
pass
img = cv2.imread('../1.jpeg', 0)
# 截图
# img = img[0:579, 315:704]
cv2.namedWindow('res')
cv2.createTrackbar('max', 'res', 127, 255, nothing)
cv2.createTrackbar('min', 'res', 127, 255, nothing)
# img = cv2.resize(img, (640, 360))
maxVal = 200
minVal = 100
while True:
key = cv2.waitKey(1) & 0xff
if key == ord(" "):
break
maxVal = cv2.getTrackbarPos('min', 'res')
minVal = cv2.getTrackbarPos('max', 'res')
ret, edge = cv2.threshold(img, minVal, maxVal, cv2.THRESH_BINARY)
cv2.imshow('res', edge)