Python – Uses openCV Python binding (bind) to save frames from the webcam to disk

Uses openCV Python binding (bind) to save frames from the webcam to disk… here is a solution to the problem.

Uses openCV Python binding (bind) to save frames from the webcam to disk

I’m trying to save frames from my webcam as jpg or png or some other format using opencv. This turned out to be harder than I thought, although here are examples of Capturing a single image from my webcam in Java or Python

I’m trying to do this :

if __name__ == "__main__":
print "Press ESC to exit ..."

# create windows
cv.NamedWindow('Raw', cv.CV_WINDOW_AUTOSIZE)
cv.NamedWindow('Processed', cv.CV_WINDOW_AUTOSIZE)

# create capture device
device = 0 # assume we want first device
capture = cv.CaptureFromCAM(0)
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH, 640)
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT, 480)

# check if capture device is OK
if not capture:
    print "Error opening capture device"

while 1:
    # do forever

# capture the current frame
    frame = cv.QueryFrame(capture)
    if frame is None:

# mirror
    cv.Flip(frame, None, 1)

# face detection

# display webcam image
    cv.ShowImage('Raw', frame)

# handle events
    k = cv.WaitKey(10)

if k == 0x1b: # ESC
        print 'ESC pressed. Exiting ...'

if k == 0x63 or k == 0x43:
        print 'capturing!'
        s, img =
        if s:
            cv.SaveImage("r'C:\test.jpg", img) 

As you can see, I tried using the code modification suggested by Froyo in another issue so that it captures an image when I press the letter c. It doesn’t work and I can’t find the documentation to make it work.

Seek help!
Thank you so much


Change your save section as follows:

if k == 0x63 or k == 0x43:
    print 'capturing!'

It worked well for me. Since you have already captured the frame for detection, you need to capture it again to save this frame.

cv.CaptureFromCam() and cv.VideoCapture() are also different. They cannot be confused.

Related Problems and Solutions