How to store webcam video with OpenCV in Python

2020-07-24 04:58发布

问题:

I've got a script in Python which reads out my webcam and shows it in a window. I now want to store the results, so following this tutorial I wrote the following code:

import cv2
import imutils
camera = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object to save the video
fourcc = cv2.VideoWriter_fourcc(*'XVID')
video_writer = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))

while True:
    try:
        (grabbed, frame) = camera.read()  # grab the current frame
        frame = imutils.resize(frame, width=640, height=480)
        cv2.imshow("Frame", frame)  # show the frame to our screen
        key = cv2.waitKey(1) & 0xFF  # I don't really have an idea what this does, but it works..
        video_writer.write(frame)  # Write the video to the file system
    except KeyboardInterrupt:
        break

# cleanup the camera and close any open windows
camera.release()
video_writer.release()
cv2.destroyAllWindows()
print "\n\nBye bye\n"

This perfectly shows the real time video footage from my webcam in a new window. But writing the video file seems to fail. It does create a file called output.avi, but the file is empty (zero bytes) and on the command line I see the following errors:

OpenCV: Frame size does not match video size.
OpenCV: Frame size does not match video size.
OpenCV: Frame size does not match video size.
etc.

I clearly resize the frame to the size in which I want to save the video (640x480) so I'm not sure why it wouldn't match.

When I run the script again (so in this case the empty output.avi already exists), it shows these errors:

2017-04-17 10:57:14.147 Python[86358:5848730] AVF: AVAssetWriter status: Cannot Save
2017-04-17 10:57:14.332 Python[86358:5848730] mMovieWriter.status: 3. Error: Cannot Save
2017-04-17 10:57:14.366 Python[86358:5848730] mMovieWriter.status: 3. Error: Cannot Save
2017-04-17 10:57:14.394 Python[86358:5848730] mMovieWriter.status: 3. Error: Cannot Save
etc.

In the tutorial it says that the Four digit FourCC code is used to specify the video codec which is platform dependent and that the list of available codes can be found in fourcc.org. I'm on OSX so I tried a bunch of different codec-codes: DIVX, XVID, MJPG, X264, WMV1, WMV2. But unfortunately none of them work for me. They all give the same errors, except for MJPG, which gives me the following error:

OpenCV Error: Assertion failed (img.cols == width && img.rows == height && channels == 3) in write, file /tmp/opencv3-20170216-77040-y1hrk1/opencv-3.2.0/modules/videoio/src/cap_mjpeg_encoder.cpp, line 829
Traceback (most recent call last):
  File "store_video.py", line 15, in <module>
    video_writer.write(frame)  # Write the video to the file system
cv2.error: /tmp/opencv3-20170216-77040-y1hrk1/opencv-3.2.0/modules/videoio/src/cap_mjpeg_encoder.cpp:829: error: (-215) img.cols == width && img.rows == height && channels == 3 in function write

Does anybody know what could be wrong here? All tips are welcome!

回答1:

It's probably because you built OpenCV with AVFoundation and it doesn't support XVID or other codec. You can try mp4v and m4v extension.

import cv2
camera = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object to save the video
fourcc = cv2.VideoWriter_fourcc('m','p','4','v')
video_writer = cv2.VideoWriter('output.m4v', fourcc, 30.0, (640, 480))

while True:
        (grabbed, frame) = camera.read()  # grab the current frame
        frame = cv2.resize(frame, (640,480))
        cv2.imshow("Frame", frame)  # show the frame to our screen
        key = cv2.waitKey(33) & 0xFF  # I don't really have an idea what this does, but it works..
        video_writer.write(frame)  # Write the video to the file system
        if key==27:
            break;

# cleanup the camera and close any open windows
camera.release()
video_writer.release()
cv2.destroyAllWindows()
print("\n\nBye bye\n")

On the other note, the error

OpenCV Error: Assertion failed (img.cols == width && img.rows == height && channels == 3) in write, file /tmp/opencv3-20170216-77040-y1hrk1/opencv-3.2.0/modules/videoio/src/cap_mjpeg_encoder.cpp, line 829

means that you messed up the dimension with

frame = imutils.resize(frame, width=640, height=480)

You can try cv2.resize as I used in my code. There's no need to use another library when cv2 can do that already.