我们将看到如何使用 python open-cv 将对象与图像中的背景分离,它以 cv2(计算机视觉)库的形式存在。
您可以使用库的threshold()方法cv2将对象与图像中的背景分开。要使用 cv2 库,您需要使用import statement.
threshold()
cv2
import statement
现在让我们先看看方法的语法和返回值cv2 threshold(),然后我们将继续示例。
cv2 threshold()
cv2.threshold(src, thresholdValue, maxVal, thresholdingTechnique)
您需要将四个参数传递给cv2 threshold()方法。
src:输入灰度图像数组。
src:
thresholdValue:提及用于对像素值进行分类的值。
thresholdValue:
maxVal:如果像素值大于(有时小于)阈值,则要给出的值。
maxVal:
thresholdingTechnique:
要应用的阈值类型。
有 5 种不同的简单阈值技术:
cv2.THRESH_BINARY:
cv2.THRESH_BINARY_INV:
cv2.THRESH_TRUNC:
cv2.THRESH_TOZERO:
cv2.THRESH_TOZERO_INV:
此方法返回一个包含 2 个值的元组,其中第一个值是阈值,第二个值是修改后的图像数组。
现在让我们看看 Python 代码:
# 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)
输出:
# 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)
同样,您可以应用其他给定的阈值技术并查看它们的结果。
这就是关于 cv2 threshold() 方法的全部内容。
原文链接:https://codingdict.com/