Ask Your Question

How to set webcam codec in OpenCV 3.1.0 Python?

asked 2016-08-25 18:07:31 -0600

bb12jo gravatar image

I have a problem with my webcams using the uncompressed YUYV codec in OpenCV Python which makes it so that I have horrible frame rates. I would like to set the codec to MJPG, but I can't seem to figure out how. Here is what I have tried(along with variations of it)

import cv2 #Opencv 3.1.0
import matplotlib.pyplot as plt
import numpy as np
vid = cv2.VideoCapture(0)
vid.set(6, cv2.CV_FOURCC('M','J', 'P', 'G'))#Should set the codec, but it doesn't

while True:
    _, img =

    cv2.imshow('image', img)

    k = cv2.waitKey(5) & 0xFF
    if k == 27:


When I run it, I get cv2 has no attribute to CV_FOURCC. I have been using this as a reference, but it doesn't really explain what I am supposed to pass in after I input the 6 in the vid.set(). I have the cv2.CV_FOURCC, but I just guessed that is what it wanted. Any help would be greatly appreciated!

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2016-08-26 00:03:48 -0600

berak gravatar image

updated 2016-08-26 00:25:31 -0600

you can try either:

 cv2.VideoWriter_fourcc('M','J', 'P', 'G')

or the numerical:


but chances are low, that this is supported from your capture driver / os.

(please also check the return value from cap.set(...))

edit flag offensive delete link more

Question Tools

1 follower


Asked: 2016-08-25 18:07:31 -0600

Seen: 3,575 times

Last updated: Aug 26 '16