OpenCV Canny边缘检测

OpenCV Canny边缘检测

边缘检测指的是识别图像中物体的边界。我们将学习使用Canny边缘检测技术进行边缘检测。Canny边缘检测函数的语法如下:

edges = cv2.Canny('/path/to/img', minVal, maxVal, apertureSize, L2gradient)

参数-

  • /path/to/img: 图像文件路径(必需)
  • minVal: 最小强度梯度(必需)
  • maxVal: 最大强度梯度(必需)
  • aperture: 可选参数
  • L2gradient: 默认值为false,如果值为true,则Canny()使用一种更耗费计算资源的方程来检测边缘,从而提供更准确的结果。

示例1

import cv2
img = cv2.imread(r'C:\Users\DEVANSH SHARMA\cat_16x9.jpg')
edges = cv2.Canny(img, 100, 200)

cv2.imshow("Edge Detected Image", edges)
cv2.imshow("Original Image", img)
cv2.waitKey(0)  # waits until a key is pressed
cv2.destroyAllWindows()  # destroys the window showing image

输出:

OpenCV Canny边缘检测

示例2:实时边缘检测

# import libraries of python OpenCV  
import cv2

# import Numpy by alias name np
import numpy as np

# capture frames from a camera 
cap = cv2.VideoCapture(0)

# loop runs if capturing has been initialized 
while (1):

    # reads frames from a camera 
    ret, frame = cap.read()

    # converting BGR to HSV 
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    # define range of red color in HSV 
    lower_red = np.array([30, 150, 50])
    upper_red = np.array([255, 255, 180])

    # create a red HSV colour boundary and  
    # threshold HSV image 
    mask = cv2.inRange(hsv, lower_red, upper_red)

    # Bitwise-AND mask and original image 
    res = cv2.bitwise_and(frame, frame, mask=mask)

    # Display an original image 
    cv2.imshow('Original', frame)

    # discovers edges in the input image image and 
    # marks them in the output map edges 
    edges = cv2.Canny(frame, 100, 200)

    # Display edges in a frame 
    cv2.imshow('Edges', edges)

    # Wait for Esc key to stop 
    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

# Close the window 
cap.release()

# De-allocate any associated memory usage 
cv2.destroyAllWindows()

输出:

OpenCV Canny边缘检测

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程