This question already has answers here:
How to correctly check if a camera is available?

(4个答案)


去年关闭。




我目前有一个程序,该程序接受视频文件的输入,然后将遮罩颜色,因此有3个不同的窗口:一个仅显示绿色,一个仅显示黄色和一个仅显示红色。这部分工作正常,但是我只是想获取它,以便如果它在给定路径下找不到文件,它将仅使用网络摄像头。我试过使用FileNotFoundError使用try except语句,但这似乎不适用于OpenCV。
import cv2
import numpy as np

try:
    device = cv2.VideoCapture(r"%Downloads%\Traffic light changing between green yellow and red.mp4")
except FileNotFoundError:
    device = cv2.VideoCapture(0)

while True:
    ret, frame = device.read()
    if not ret:
        break
    hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
    lower_range_red = np.array([100,100,175])
    upper_range_red = np.array([255,255,255])
    lower_range_yellow = np.array([5,100,225])
    upper_range_yellow = np.array([50,255,255])
    lower_range_green = np.array([40,50,200])
    upper_range_green = np.array([120,200,255])

    mask_red = cv2.inRange(hsv, lower_range_red, upper_range_red)
    mask_yellow = cv2.inRange(hsv, lower_range_yellow, upper_range_yellow)
    mask_green = cv2.inRange(hsv, lower_range_green, upper_range_green)

    result_red = cv2.bitwise_and(frame,frame,mask=mask_red)
    result_yellow = cv2.bitwise_and(frame,frame,mask=mask_yellow)
    result_green = cv2.bitwise_and(frame,frame,mask=mask_green)
    cv2.imshow("Red",result_red)
    cv2.imshow("Yellow",result_yellow)
    cv2.imshow("Green",result_green)

    if cv2.waitKey(1) == 27 & 0xFF:
        break

device.release()
cv2.destroyAllWindows()

最佳答案

您可以检查它是否正确打开。

if device.isOpened()

关于python - 等效于OpenCV for Python中的FileNotFoundError ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54219641/

10-08 22:39