Warm tip: This article is reproduced from serverfault.com, please click

Changing codec of webcam is not possible using OpenCV/Python

发布于 2020-06-13 10:06:21

I am using windows 10 and python 3.7 / OpenCV4 and a Logitech C922 webcam. While the cam seems to provide 30 fps using the windows camera app, i can not get more than 5-6 fps using OpenCV. Resolution is set to FHD.

cam = cv2.VideoCapture(cv2.CAP_DSHOW+0)
while(1):
    ret,frame = cam.read()
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

In another post I found the solution to change the codec to MJPG. However, the camera does not accept changing the codec. I tried:

cam.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('m','j','p','g'))
cam.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M','J','P','G'))
cam.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))
cam.set(cv2.CAP_PROP_FOURCC, float(cv2.VideoWriter_fourcc('m','j','p','g'))
cam.set(cv2.CAP_PROP_FOURCC, float(cv2.VideoWriter_fourcc('M','J','P','G'))
cam.set(cv2.CAP_PROP_FOURCC, 1196444237.0)

The camera always returns "844715353.0"

How can I achieve higher fps?

Questioner
Matt
Viewed
0
Diego L. Guarin 2020-12-02 04:52:11

It seems that order matters. As I understand, OpenCv uses ffmpeg in the background. In ffmpeg the command should be something like this:

ffmpeg -f dshow -framerate 60 -video_size 1280x720 -input_format mjpeg -i video="my webcam" out.mkv

So that your OpenCV code should be something like this

my_cam_index = 0 
cap = cv2.VideoCapture(my_cam_index, cv2.CAP_DSHOW)
cap.set(cv2.CAP_PROP_FPS, 60.0) 
cap.set(cv2.CAP_PROP_FRAME_WIDTH,1280)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT,720) 
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter.fourcc('M','J','P','G'))