Python cv2 .mp4 codec unable to be displayed in browser

Question:

When I record my webcam using the below Python code, it saves it into webcam.mp4.
On my local computer I am able to view the video, but when I display it in my browser, it doesn’t work. It seems, that the codec is wrong, but I have not figured out why, nor how to get it correct.

The Python code

    global rec_bool
    rec_bool = False

    def timer(seconds):
        global rec_bool
        rec_bool = True
        time.sleep(seconds)
        rec_bool = False

    seconds = 3
    timer_thread = threading.Thread(target=timer, args=(seconds,)).start()
    vid_capture = cv2.VideoCapture(0)
    vid_cod = cv2.VideoWriter_fourcc(*'mp4v')
    output = cv2.VideoWriter("webcam.mp4", vid_cod, 20.0, (640,480))
    while(rec_bool == True):
        ret,frame = vid_capture.read()
        
        output.write(frame)

    vid_capture.release()
    output.release()
    cv2.destroyAllWindows()

The HTML code

<iframe class="video" id="webcam_video" src="/static/videos/webcam.mp4" frameborder="0" allowfullscreen></iframe>

It just shows a loading symbol. When I on the other hand use curl to download it, it works perfectly fine. I have tried with other mp4 files, and they work, like they should.

Asked By: root

||

Answers:

Not all codecs work in web browser. See in Wikipedia: HTML5 video

For all browsers should work codec H.264 so you can try

vid_cod = cv2.VideoWriter_fourcc(*'H264')

If this can’t work – ie. when cv2 was compiled without this codec – then you can convert it with external tools like ffmpeg

In system console/shell

ffmpeg -i webcam.mp4 -vcodec libx264 -f mp4 output.mp4

In code

os.system("ffmpeg -i webcam.mp4 -vcodec libx264 -f mp4 output.mp4")

or

import subproces

# with `shell=True`
subproces.run("ffmpeg -i webcam.mp4 -vcodec libx264 -f mp4 output.mp4", shell=True)

# without `shell=True`
subproces.run( ["ffmpeg", "-i", "webcam.mp4", "-vcodec", "libx264", "-f", "mp4", "output.mp4"] )

or using modules like ffmpeg-python or MoviePy which use ffmpeg.


BTW: ffmpeg installs also program ffprobe which may show details about codecs used in file.

 ffprobe webcam.mp4

EDIT:

You can also use ffmpeg to record from WebCam

For Linux (which I use)

ffmpeg -f v4l2 -i /dev/video0 -t 00:00:03 output.mp4

or with some settings

ffmpeg -f v4l2 -framerate 20 -video_size 640x480 -i /dev/video0 -t 00:00:03 output.mp4

3 seconds = -t 00:00:03 or -t 3

For other systems you should find information in documentation WebCam

Answered By: furas
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.