Python | cv2 canny()方法
时间:2020-02-23 14:42:13 来源:igfitidea点击:
在本教程中,我们将看到如何使用Python Open-CV检测图像中的边缘,该CV存在于CV2(计算机视觉)库中。
我们可以使用 Canny()
的方法 cv2
库检测图像中的边缘。
要使用CV2库,我们需要使用CV2库使用 import statement
。 Canny()
方法使用Canny Edge检测算法查找图像中的边缘。
有关更多信息:Canny Edge检测算法
现在让我们看看语法和返回值 cv2 canny()
方法首先,我们将继续执行示例。
语法
cv2.Canny(image, threshold1, threshold2, apertureSize, L2gradient)
参数
我们可以通过五个参数来resize()方法。
在五个参数中,前三(图像,阈值和阈值2)是强制性的;休息(Apertureaze和L2GRadient)是可选的。
必要的参数是:
image:
n维数组的源/输入图像。threshold1:
它是强度梯度的高阈值值。threshold2:
它是强度梯度的低阈值。
可选参数是:
apertureSize:
Sobel过滤器的内核(矩阵)的顺序。其默认值为(3 x 3),其值应在3到7之间为奇数。它用于查找图像渐变。过滤器用于图像的平滑和锐化。L2gradient:
这指定了查找梯度幅度的等式。 l2gradient是boolean类型,其默认值是False
。
返回值
它返回灰度边缘检测到的图像。
CV2 Canny()方法示例
现在让我们看看Python代码: Example 1:
使用 Canny()
仅限必要参数的方法。
# 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 image = cv2.imread(img_path) # show the input image on the newly created image window cv2.imshow('image window1',image) # detection of the edges img_edge = cv2.Canny(image,100,200) # show the image edges on the newly created image window cv2.imshow('image window2',img_edge)
输出:
Example 2:
使用 Canny()
方法 apertureSize
参数值以及必要的参数。
# 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 image = cv2.imread(img_path) # show the input image on the newly created image window cv2.imshow('image window1',image) # detection of the edges img_edge = cv2.Canny(image,100,200,apertureSize = 5) # show the image edges on the newly created image window cv2.imshow('image window2',img_edge)
输出 :
Example 3:
使用canny()方法 L2gradient
和 apertureSize
参数值以及必要的参数。
# 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 image = cv2.imread(img_path) # show the input image on the newly created image window cv2.imshow('image window1',image) # detection of the edges img_edge = cv2.Canny(image,100,200,apertureSize = 5, L2gradient = True) # show the image edges on the newly created image window cv2.imshow('image window2',img_edge)
输出:
Example 4:
使用 Canny()
方法 L2gradient
参数值以及必要的参数。
# 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 image = cv2.imread(img_path) # show the input image on the newly created image window cv2.imshow('image window1',image) # detection of the edges img_edge = cv2.Canny(image,100,200, L2gradient = True) # show the image edges on the newly created image window cv2.imshow('image window2',img_edge)