Search code examples
pythonopencvwebcam

Save multiple images with OpenCV and Python


I'm using OpenCV and Python to take images. However currently I can only take one picture at a time. I would like to have OpenCV to take multiple pictures. This is my current code.

import cv2.cv as cv
import time

cv.NamedWindow("camera", 1)

capture = cv.CaptureFromCAM(0)

while True:
    img = cv.QueryFrame(capture)
    cv.ShowImage("camera", img)
    cv.SaveImage('pic.jpg', img)
    if cv.WaitKey(10) == 27:
        break 

Solution

  • Your code overwrite a file. Save to different file each time. For example:

    import cv2.cv as cv
    import time
    
    cv.NamedWindow("camera", 1)
    
    capture = cv.CaptureFromCAM(0)
    
    i = 0
    while True:
        img = cv.QueryFrame(capture)
        cv.ShowImage("camera", img)
        cv.SaveImage('pic{:>05}.jpg'.format(i), img)
        if cv.WaitKey(10) == 27:
            break
        i += 1