📜  python opencv 基础6: cv2.threshold()二值图像

📅  最后修改于: 2020-08-31 05:50:45             🧑  作者: Mango

二值图像是指在图像中,灰度等级只有两种,也就是说,图像中的任何像素点的灰度值均为0或者255,分别代表黑色和白色。

二值图像一般可以用于分割、轮廓提取等。

在本节中,我们介绍opencv的threshold方法及其使用示例,以便得到我们想要的二值图像。

Threshold()参数

threshold(src, thresh, maxval, type, dst=None)
  • src: 输入的图像 (可以多通道, 8-bit or 32-bit floating point)
  • threshod: 阈值
  • maxval: 最大值
  • type: 操作的方法
  • • cv2.THRESH_BINARY(黑白二值)
    • cv2.THRESH_BINARY_INV(黑白二值反转)
    • cv2.THRESH_TRUNC (得到的图像为多像素值)
    • cv2.THRESH_TOZERO
    • cv2.THRESH_TOZERO_INV
  • dst:输出

对于maxval和type参数,我们做一些额外的说明:

示例:

import cv2

#read image
img_grey = cv2.imread('./original.png', cv2.IMREAD_GRAYSCALE)

# define a threshold, 128 is the middle of black and white in grey scale
thresh = 128

# threshold the image
img_binary = cv2.threshold(img_grey, thresh, 255, cv2.THRESH_BINARY)[1]
// retval, dst = img_binary = cv2.threshold(img_grey, thresh, 255, cv2.THRESH_BINARY)

#save image
cv2.imshow('dst',img_binary) 
cv2.waitKey(0)

输出效果如下:

说明:

cv2.threshold的返回值值为一个list,分别为retval和dst,所以我们要获取二值图像,可直接取第二个元素。

输入的图像也可以使灰度图像,要获取灰度图像,可以直接利用imread,也可以使用cvtColor函数