繁体   English   中英

从网络摄像头捕获帧,它只返回 opencv cv2.VideoCapture() 中的 1 帧

[英]Capturing frame from webcam, it return only 1 frame in opencv cv2.VideoCapture()

我是图像处理的新手。

我正在尝试按照 Python OpenCV 中的一篇论文构建交通信号灯检测。

但是我遇到了一个我无法理解的错误。

这是代码。


# TL_Detection.py

import cv2
import numpy as np 


def Video():
    try:
        cap = cv2.VideoCapture(0)
        # cap = cv2.VideoCapture('/home/aicar/Downloads/tf_test.mp4')

    except:
        print('no cam error')
        return

    # cap.set(3, 480)
    # cap.set(4, 320)

    frameWidth = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frameHeight = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    size = (frameWidth, frameHeight)
    cap.set(3, frameWidth)
    cap.set(4, frameHeight)

    cnt = 0

    # while cap.isOpened():
    while True:
        ret, frame = cap.read()
        # if not cap.isOpened():
        #     cap.open('/home/aicar/Downloads/tf_test.mp4')
        cv2.imshow('frame', frame)

        print(ret, cnt)
        if not ret:
            print('no ret error')
            break


        cnt += 1
        cap.release()
        cv2.destroyAllWindows()
        
Video()

此代码返回如下。

True 0
OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow, file /home/aicar/opencv/opencv-3.4.0/modules/highgui/src/window.cpp, line 339
Traceback (most recent call last):
  File "/home/aicar/codes_juyeong/TL_detection.py", line 53, in <module>
    Video()
  File "/home/aicar/codes_juyeong/TL_detection.py", line 33, in Video
    cv2.imshow('frame', frame)
cv2.error: /home/aicar/opencv/opencv-3.4.0/modules/highgui/src/window.cpp:339: error: (-215) size.width>0 && size.height>0 in function imshow

为什么只获得第一帧后无法获得帧? 网络摄像头已正确连接。

需要你的帮助。 谢谢。

你太早释放你的上限,它在真正的循环中。 所以让它脱离这个循环,你的程序将毫无问题地运行。

如果这个回答对你有帮助,请采纳。

要逐帧捕获,请尝试以下代码:

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while(True):
# Capture frame-by-frame
   ret, frame = cap.read()

# Our operations on the frame come here
   gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

# Display the resulting frame
   cv2.imshow('frame',gray)
   if cv2.waitKey(1) & 0xFF == ord('q'):
       break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
# while cap.isOpened():
while True:
    ret, frame = cap.read()
    # if not cap.isOpened():
    #     cap.open('/home/aicar/Downloads/tf_test.mp4')
    cv2.imshow('frame', frame)

    print(ret, cnt)
    if not ret:
        print('no ret error')
        break


    cnt += 1

# take it out of while loop
cap.release()
cv2.destroyAllWindows()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM