I'm trying to learn OpenCV. How do I capture an image frame from a builtin webcam using cv2.VideoCapture()
?
import cv2, time
video = cv2.VideoCapture(0, cv2.CAP_DSHOW)
video.release()
check,frame = video.read()
print(check)
print(frame)
time.sleep(3)
cv2.destroyAllWindows()
This produces the following output:
False
None
Why does it return False
?
Read the docs for VideoCapture::release
. According to them it
Closes video file or capturing device.
That's not what you want. Remove the video.release()
. Then VideoCapture::read()
should succeed.
Starting out with OpenCV it's often easiest to start from some tutorial code and then modify as needed. For example, this tutorial is the first thing that comes up for a search for "OpenCV VideoCapture tutorial":
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.