简体   繁体   中英

Why can't I capture with my webcam more than once with OpenCV in Python?

I tried to write a small Python program which would allow me to start the webcam and capture and save the image to a.png file:

import cv2

cap = cv2.VideoCapture(0)
for i in range(3):
    ret, frame = cap.read()
    cap.release()
    if ret == True:
        cv2.imwrite(str(i) + 'image.png', frame)
    else:
        print("Webcam not working")
        print(ret)

but when I execute it it would only save the image once under 0image.png and then display this in the console:

Webcam not working
False
Webcam not working
False

What am I doing wrong?

The cap.release() functions helps you to free up your system, ie , the camera device resource, and if not done so, then it will raise errors like Device or resource busy if you try to create a new instance. So, you need to remove the cap.release() from your loop and place it at the end of your program. This should work.

 import cv2 cap = cv2.VideoCapture(0) for i in range(3): ret, frame = cap.read() if ret == True: cv2.imwrite(str(i) + 'image.png', frame) else: print("Webcam not working") print(ret)` cap.release()

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.

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