OpenCV Canny 边缘检测 Python

OpenCV Canny Edge Detection Python

我收到这个错误:

OpenCV Error: Unsupported format or combination of formats() in unknown function, file C:\slave\WinInstallerMegaPack\src\opencv\modules\imgproc\src\canny.cpp, line 67 Traceback (most recent call last): edges= cv2.Canny(frame,100,100) cv2.error : C:\ slave\WinInstallerMegaPack\srx\opencv\modules\imgproc\src\canny.cpp:67: error: (-210)

当我运行这段代码时:

import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while(1):
   _, frame = cap.read()    
   cv2.imshow('Original',frame)
   edges = cv2.Canny(frame,100,100)
   cv2.imshow('Edges',edges)
   k = cv2.waitKey(5) & 0xFF
   if k == 27:
      break

cv2.destroyAllWindows()
cap.release()

Canny 需要灰度图像作为输入,但您的 frame 是 3 通道 (BGR) 图像。在将其传递给 Canny 之前,您需要将其转换为灰度:

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 100, 100)

作为旁注,请记住 Canny 阈值用于滞后,因此您可能希望将 first_threshold 设置为 [0.25 - 0.5] * second_threshold

edges = cv2.Canny(gray, 100, 200)