Python | cv2 threshold()方法 阈值方法
时间:2020-02-23 14:42:15 来源:igfitidea点击:
在本教程中,我们将看到如何使用Python Open-CV将对象与图像中的背景分开,这是CV2(计算机视觉)库存在的。
我们可以使用 threshold()的方法 cv2库将对象从图像中的背景分隔。
要使用CV2库,我们需要使用CV2库使用 import statement。
现在让我们看看语法和返回值 cv2 threshold()方法首先,我们将继续执行示例。
语法
cv2.threshold(src, thresholdValue, maxVal, thresholdingTechnique)
参数
我们需要传递四个参数 cv2 threshold()方法。
src:输入灰度图像阵列。thresholdValue:提及用于对像素值分类的值。maxVal:如果像素值大于(有时小于)阈值,则要赋予的值。thresholdingTechnique:要应用的阈值的类型。
有5种不同的简单阈值技术是:
cv2.THRESH_BINARY:如果像素强度大于设置阈值,则值设置为255,否则设置为0(黑色)。cv2.THRESH_BINARY_INV:倒置或者相反的cv2.Thresh_binary。<li。cv2.THRESH_TRUNC:如果像素强度值大于阈值,则它被截断到阈值。像素值被设置为与阈值相同。所有其他值保持不变。cv2.THRESH_TOZERO:像素强度设置为0,对于所有像素强度,小于阈值。cv2.THRESH_TOZERO_INV:倒置或者相反的cv2.thresh_tozero。
返回值
该方法返回2个值的元组,其中第1个值被给出阈值,第二值是修改图像阵列。
CV2阈值()方法示例
现在让我们看看Python代码:
示例1:使用cv2.Thresh_binary阈值技术。
# import computer vision library(cv2) in this code
import cv2
# main code
if __name__ == "__main__" :
# mentioning absolute path of the image
img_path = "C:\Users\user\Desktop\flower.jpg"
# read/load an image in grayscale mode
grey_img = cv2.imread(img_path,0)
# show the Input image on the newly created image window
cv2.imshow('Input',grey_img)
# applying cv2.THRESH_BINARY thresholding techniques
ret, thresh_img = cv2.threshold(grey_img, 128, 255, cv2.THRESH_BINARY)
# show the Output image on the newly created image window
cv2.imshow('Output',thresh_img)
示例2:使用cv2.Thresh_binary_inv阈值技术。
# import computer vision library(cv2) in this code
import cv2
# main code
if __name__ == "__main__" :
# mentioning absolute path of the image
img_path = "C:\Users\user\Desktop\flower.jpg"
# read/load an image in grayscale mode
grey_img = cv2.imread(img_path,0)
# show the Input image on the newly created image window
cv2.imshow('Input',grey_img)
# applying cv2.THRESH_BINARY_INV thresholding techniques
ret, thresh_img = cv2.threshold(grey_img, 128, 255, cv2.THRESH_BINARY_INV)
# show the Output image on the newly created image window
cv2.imshow('Output',thresh_img)
同样,我们可以应用其他给定的阈值化技术并查看其结果。

