OpenCV第六篇:阈值函数

阳光穿透心脏的1/2处 2024-04-08 11:34 73阅读 0赞

阈值的作用是根据设定的值处理图像的灰度值,比如灰度大于某个数值像素点保留。通过阈值以及有关算法可以实现从图像中抓取特定的图形,比如去除背景等。实例图片:

1.普通阈值函数:threshold(像素矩阵,起始阈值,最大值,算法类型)—>retval, threshold" class="reference-link">在这里插入图片描述 1.普通阈值函数:threshold(像素矩阵,起始阈值,最大值,算法类型)—>retval, threshold

  1. import cv2
  2. if __name__ == '__main__':
  3. img = cv2.imread('1.png')
  4. retval, threshold = cv2.threshold(img, 12, 255, cv2.THRESH_BINARY)
  5. cv2.imshow('original', img)
  6. cv2.imshow('threshold', threshold)
  7. cv2.waitKey(0)
  8. cv2.destroyAllWindows()

583c488c6db84d00ac703eb88b63d2b5.png

使用图片的灰度图试试:

  1. import cv2
  2. if __name__ == '__main__':
  3. img = cv2.imread('1.png')
  4. # 灰度图
  5. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  6. retval, threshold = cv2.threshold(gray, 12, 255, cv2.THRESH_BINARY)
  7. cv2.imshow('original', img)
  8. cv2.imshow('threshold', threshold)
  9. cv2.waitKey(0)
  10. cv2.destroyAllWindows()

93de28482d894dbb960338c61a897e07.png

2.自适应阈值函数:adaptivthreshold()

  1. import cv2
  2. if __name__ == '__main__':
  3. img = cv2.imread('1.png')
  4. # 灰度图
  5. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  6. threshold = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1)
  7. cv2.imshow('original', img)
  8. cv2.imshow('threshold', threshold)
  9. cv2.waitKey(0)
  10. cv2.destroyAllWindows()

bc04394087714ea892a591b3c7060728.png

发表评论

表情:
评论列表 (有 0 条评论,73人围观)

还没有评论,来说两句吧...

相关阅读