阈值的作用是根据设定的值处理图像的灰度值,比如灰度大于某个数值像素点保留。通过阈值以及有关算法可以实现从图像中抓取特定的图形,比如去除背景等。实例图片:
1.普通阈值函数:threshold(像素矩阵,起始阈值,最大值,算法类型)-->retval, threshold
import cv2
if __name__ == '__main__':
img = cv2.imread('1.png')
retval, threshold = cv2.threshold(img, 12, 255, cv2.THRESH_BINARY)
cv2.imshow('original', img)
cv2.imshow('threshold', threshold)
cv2.waitKey(0)
cv2.destroyAllWindows()
使用图片的灰度图试试:
import cv2
if __name__ == '__main__':
img = cv2.imread('1.png')
# 灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
retval, threshold = cv2.threshold(gray, 12, 255, cv2.THRESH_BINARY)
cv2.imshow('original', img)
cv2.imshow('threshold', threshold)
cv2.waitKey(0)
cv2.destroyAllWindows()
2.自适应阈值函数:adaptivthreshold()
import cv2
if __name__ == '__main__':
img = cv2.imread('1.png')
# 灰度图
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
threshold = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1)
cv2.imshow('original', img)
cv2.imshow('threshold', threshold)
cv2.waitKey(0)
cv2.destroyAllWindows()