Capturing a single frame with Python (using a webcam)

半城伤御伤魂 提交于 2020-02-06 08:51:08

问题


I checked other solutions, but they weren't answering my question. My issue is that whenever I try to capture just one frame from a video (I want to basically take a picture with my webcam) I just get a black window.

Code -

import cv2


cam = cv2.VideoCapture(0)
frame = cam.read()[1]
cv2.imwrite('img2.png', frame)
cv2.imshow("img1", frame)

screenshot - https://imgur.com/kfeXYvQ

My webcam is USB, 720p at 30fps.

Thanks.


回答1:


One of two things. It might be that you need to add a waitKey() after cv2.imshow(). Alternatively, you aren't checking the return from the camera for any errors. It could be a connection problem. Here are the two things to do.

import cv2

cam = cv2.VideoCapture(0)
retval, frame = cam.read()
if retval != True:
    raise ValueError("Can't read frame")

cv2.imwrite('img2.png', frame)
cv2.imshow("img1", frame)
cv2.waitKey()

The waitKey() function halts the program until a user has entered a key in the window.



来源:https://stackoverflow.com/questions/47824785/capturing-a-single-frame-with-python-using-a-webcam

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!