The problem maybe is with the codec of the camera stream and not with the FPS itself, for example, if your camera only supports YUYV it is probably that you could only work with some specific FPS, try with the app guvcview to check this in a GUI.

Try to change the codec to MJPG and then change the FPS using CAP_PROP_FPS. I'm using a Logitech C922 pro and this works for me to configure 1080p and 30fps, if you have other camera probably yu need to use a lower resolution to achieve 30fps:

import cv2 as cv
def decode_fourcc(v):
    v = int(v)
    return "".join([chr((v >> 8 * i) & 0xFF) for i in range(4)])

def setfourccmjpg(cap):
    oldfourcc = decode_fourcc(cap.get(cv.CAP_PROP_FOURCC))
    codec = cv.VideoWriter_fourcc(*'MJPG')
    res=cap.set(cv.CAP_PROP_FOURCC,codec)
    if res:
        print("codec in ",decode_fourcc(cap.get(cv.CAP_PROP_FOURCC)))
    else:
        print("error, codec in ",decode_fourcc(cap.get(cv.CAP_PROP_FOURCC)))
cap = cv.VideoCapture(CAMERANUM)
cu.setfourccmjpg(cap)
w=1920
h=1080
fps=30
res1=cap.set(cv.CAP_PROP_FRAME_WIDTH,w)
res2=cap.set(cv.CAP_PROP_FRAME_HEIGHT,h)
res3=cap.set(cv.CAP_PROP_FPS,fps)

then resume your normal video capture polling loop.

Answer from Francisco Carlos Calderon on Stack Overflow
🌐
GitHub
github.com › opencv › opencv › issues › 21673
cv::VideoCapture set cv::CAP_PROP_FPS is not working · Issue #21673 · opencv/opencv · GitHub
March 2, 2022 - Please try to use some sample code to setup the fps for web cameras, like: #include "opencv2/videoio.hpp" cv::VideoCapture capture; capture.open("/dev/video0"); bool success = capture.isOpened(); if (success) { capture.set(cv::CAP_PROP_FPS, 25); }
Discussions

Opencv-Python cv2.CV_CAP_PROP_FPS error - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I'm using opencv 3.2.0 and python 3.5.2 currently. When executing following code: videoCapture = cv2.VideoCapture(file_path) fps = videoCapture.get(cv2.CV_CAP_PROP_FPS) size = (int(videoCapt... More on stackoverflow.com
🌐 stackoverflow.com
Opencv Camera Properties : CAP_PROP_FOURCC Not working
One of my code related to Fiducial markers detection have following lines : codec = 0x47504A4D # MJPG cap.set(cv2.CAP_PROP_FPS, 30.0) cap.set(cv2.CAP_PROP_FOURCC, codec) cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080) This parameter setting is working fine in ... More on forums.developer.nvidia.com
🌐 forums.developer.nvidia.com
20
0
June 1, 2021
Python OpenCV video.get(cv2.CAP_PROP_FPS) returns 0.0 FPS - Stack Overflow
This is my video This is the script to find fps: import cv2 if __name__ == '__main__' : video = cv2.VideoCapture("test.mp4"); # Find OpenCV version (major_ver, minor_ver, subminor_ve... More on stackoverflow.com
🌐 stackoverflow.com
set property of cv2.VideoCapture is returning false for cv2.CAP_PROP_FPS
Expected behaviour Write here how did you expect the library to function. if fps rate of a video file is 25 ,i need to read only 10 frames per second so i set fps as 10 using set property cv2.CAP_PROP_FPS , after setting capture.read() o... More on github.com
🌐 github.com
1
January 6, 2020
🌐
GitHub
github.com › opencv › opencv › issues › 24000
.get(cv2.CAP_PROP_FPS) returns incorrect FPS · Issue #24000 · opencv/opencv · GitHub
July 17, 2023 - video_capture = cv2.VideoCapture('C:\\Users\\AShetty12\\Downloads\\raw_videos\\MOV_2564.mp4') print(video_capture.isOpened()) # returns True print(video_capture.get(cv2.CAP_PROP_FPS)) # returns 30 total_frames = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT)) print(total_frames) # returns 21784 print(video_capture.set(cv2.CAP_PROP_POS_AVI_RATIO, 1)) # returns True _ = video_capture.read() time_msec = video_capture.get(cv2.CAP_PROP_POS_MSEC) print(time_msec/(1000*total_frames)) # returns 0.03335926980046518 video_capture.get(cv2.CAP_PROP_POS_FRAMES) # returns 21785.0 · MOV_2564.mp4 · EDIT: Slight change to add the 1000 in the denominator when dividing by total frames to manually calculate fps · I report the issue, it's not a question ·
🌐
OpenCV Q&A Forum
answers.opencv.org › question › 219305 › setcv2cap_prop_fps-60-is-not-working-and-camera-feed-lagging
set(cv2.CAP_PROP_FPS, 60) is not working and camera feed lagging - OpenCV Q&A Forum
after set FPS, cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) will throw below error. OpenCV(4.1.1) /Users/travis/build/skvark/opencv-python/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'. import cv2 import os toggle = True cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_FPS, 60) while True: ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow("image", gray) if toggle: print("testing") os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''') toggle = False if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
🌐
NVIDIA Developer Forums
forums.developer.nvidia.com › robotics & edge computing › jetson systems › jetson nano
Opencv Camera Properties : CAP_PROP_FOURCC Not working - Jetson Nano - NVIDIA Developer Forums
June 1, 2021 - One of my code related to Fiducial markers detection have following lines : codec = 0x47504A4D # MJPG cap.set(cv2.CAP_PROP_FPS, 30.0) cap.set(cv2.CAP_PROP_FOURCC, codec) cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080) This parameter setting is working fine in other hardware platforms.
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
Cannot get frame from cv2 - Raspberry Pi Forums
June 17, 2023 - <class 'cv2.VideoCapture'> True 640 Traceback (most recent call last): File "/home/pi/./bodycam.py", line 21, in <module> cv2.imwrite("/home/pi/test.png", img) cv2.error: OpenCV(4.7.0) /io/opencv/modules/imgcodecs/src/loadsave.cpp:783: error: (-215:Assertion failed) !_img.empty() in function 'imwrite' So it means that the camera is opend and works but the cap.read() fails. I get the same error from lokal or ssh console. What could this be? Thanks? Edit: if I try fps = int(cap.get(cv2.CAP_PROP_FPS)) it gives me an error it can not get camera fps.
🌐
LearnOpenCV
learnopencv.com › home › find frame rate (frames per second-fps) in opencv (python/c++)
Find frame rate (frames per second-fps) in OpenCV (Python/C++)
July 31, 2026 - The documentation says that get(CAP_PROP_FPS) gives the frames per second. Now that is true for video files, but not for webcams. For webcams and many other connected cameras, you have to calculate the frames per second manually. You can read a certain number of frames from the video and see how much time has elapsed to calculate frames per second. #!/usr/bin/env python import cv2 import time if __name__ == '__main__' : # Start default camera video = cv2.VideoCapture(0); # Find OpenCV version (major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.') # With webcam get(CAP_PROP_FPS) does not work.
Find elsewhere
Top answer
1 of 6
47

Setting a frame rate doesn't always work like you expect. It depends on two things:

  1. What your camera is capable of outputting.
  2. Whether the current capture backend you're using supports changing frame rates.

So point (1). Your camera will have a list of formats which it is capable of delivering to a capture device (e.g. your computer). This might be 1920x1080 @ 30 fps or 1920x1080 @ 60 fps and it also specifies a pixel format. The vast majority of consumer cameras do not let you change their frame rates with any more granularity than that. And most capture libraries will refuse to change to a capture format that the camera isn't advertising.

Even machine vision cameras, which allow you much more control, typically only offer a selection of frame rates (e.g. 1, 2, 5, 10, 15, 25, 30, etc). If you want a non-supported frame rate at a hardware level, usually the only way to do it is to use hardware triggering.

And point (2). When you use cv.VideoCapture you're really calling a platform-specific library like DirectShow or V4L2. We call this a backend. You can specify exactly which backend is in use by using something like:

cv2.VideoCapture(0 + cv2.CAP_DSHOW)

There are lots of CAP_X's defined, but only some will apply to your platform (e.g CAP_V4L2 is for Linux only). On Windows, forcing the system to use DirectShow is a pretty good bet. However as above, if your camera only reports it can output 30fps and 60fps, requesting 10fps will be meaningless. Worse, a lot of settings simply report True in OpenCV when they're not actually implemented. You've seen that most of the time reading parameters will give you sensible results though, however if the parameter isn't implemented (e.g exposure is a common one that isn't) then you might get nonsense.

You're better off waiting for a period of time and then reading the last image.

Be careful with this strategy. Don't do this:

while capturing:
    res, image = cap.read()
    time.sleep(1)

you need to make sure you're continually purging the camera's frame buffer otherwise you will start to see lag in your videos. Something like the following should work:

frame_rate = 10
prev = 0

while capturing:

    time_elapsed = time.time() - prev
    res, image = cap.read()

    if time_elapsed > 1./frame_rate:
        prev = time.time()

        # Do something with your image here.
        process_image()

For an application like a hand detector, what works well is to have a thread capturing images and the detector running in another thread (which also controls the GUI). Your detector pulls the last image captured, runs and display the results (you may need to lock access to the image buffer while you're reading/writing it). That way your bottleneck is the detector, not the performance of the camera.

2 of 6
7

I could not set the FPS for my camera so I manage to limit the FPS based on time so that only 1 frame per second made it into the rest of my code. It is not exact, but I do not need exact, just a limiter instead of 30fps. HTH

import time

fpsLimit = 1 # throttle limit
startTime = time.time()
cv = cv2.VideoCapture(0)
While True:
    frame = cv.read
    nowTime = time.time()
    if (int(nowTime - startTime)) > fpsLimit:
        # do other cv2 stuff....
        startTime = time.time() # reset time
🌐
Reddit
reddit.com › r/computervision › speeding up frame capture in opencv
r/computervision on Reddit: Speeding up frame capture in opencv
January 15, 2020 -

I'm working on an application in python using opencv for use in athletic coaching. I'd like it to run at 60fps, but I can't seem to get it to that speed. I've determined that the part that is slowing everything down is the capture process; frames aren't getting from the camera to the cpu fast enough. All testing I've done so far indicates that the processing and the rendering are not the bottleneck; it's specifically the video input that is slowing everything down.

Now, I know it is possible for the camera to run at 60fps, because when I open up the same camera in guvcview (at the same resolution), I can get a full 60fps.

I don't want to share my entire project, but here's the part that manages frame capture: https://pastebin.com/nnx32rQK. My main app calls the get_frame() function in its own thread. I'm running this on an intel NUC6CAYH (celeron CPU, 2.3 ghz), running linux.

Any help would be welcome!

EDIT: I went into more detail below, but it looks like having the cap.read() within the Feed class is a whole lot slower than just accessing cap.read() directly..... and I have no idea why

🌐
OpenCV
forum.opencv.org › python
When cap.read() is not as fast as the FPS of a camera - Python - OpenCV
October 12, 2021 - Hello everyone. I have a question regarding the OpenCV VideoCapture class. Any answer will be helpful. Suppose that we have the following code import cv2 import time cap = cv2.VideoCapture('/dev/video0', cv2.V4L2) cap.set(cv2.CAP_PROP_FPS, 30.0) while True: ret, frame = cap.read() time.sleep(0.1) My question is that, what is actually happening inside the camera when the cap.read() loop is way slower than the actual FPS?
🌐
GitHub
github.com › opencv › opencv › issues › 26250
Windows get camera cv2.CAP_PROP_FPS incorrect value for low fps. · Issue #26250 · opencv/opencv · GitHub
October 4, 2024 - from datetime import datetime,timedelta import cv2 cap = cv2.VideoCapture(0) cap.grab() # Remove this line to get correct real FPS cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) cap.set(cv2.CAP_PROP_BUFFERSIZE, 1) cap.set(cv2.CAP_PROP_FPS, 2) # Set low FPS print("Real fps: ", cap.get(cv2.CAP_PROP_FPS)) for i in range(100): cv2.waitKey(1) cap.grab() # Grab a frame now = datetime.now() print(f'{now.strftime("%M:%S")} ') Typical output: Click to expand · python.exe : [ WARN:0@3.110] global cap_msmf.cpp:929 CvCapture_MSMF::initStream Failed to select stream 0 AB@>:
Top answer
1 of 4
19

A bit too late but searching on same topic (not specific to Vivotek Camera but more on mpeg problem with openCV) :

  • Video is encoded
  • OpenCV uses FFMPEG
  • Encoding use key frames
  • When skipping some frames encoding can't give you the exact frame you want

see similar question :

  • Getting individual frames using CV_CAP_PROP_POS_FRAMES in cvSetCaptureProperty

  • How can I get one single frame from a video file?

  • Problem with CV_CAP_PROP_POS_FRAMES setting next frame number

    desired position        key frame (this is where the cursor will stop)
     |   |                       |                    |
     |   >                       |                    |
     |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
    

    Sample code using openCV 2.4.8 / VS2013 with trackbar :

  • tested with AVI format [MPEG4 Video (H264)] : setting frame position works fine
  • tested with MPG format [MPEG1/MPEG2] : setting frame position works fine

    double currentPos = capture.get(CV_CAP_PROP_POS_FRAMES);
    std::cout << "CV_CAP_PROP_POS_FRAMES = " << currentPos << std::endl;
    
    // position_slider 0 - 100
    double noFrame = position_slider*nbFrames / 100;
    
    // solution 1
    bool success = capture.set(CV_CAP_PROP_POS_FRAMES, noFrame);
    // solution 2
    double frameRate = capture.get(CV_CAP_PROP_FPS);
    double frameTime = 1000.0 * noFrame / frameRate;
    bool success = capture.set(CV_CAP_PROP_POS_MSEC, frameTime);
    
    if (!success) {
        std::cout << "Cannot set frame position from video file at " << noFrame << std::endl;       
        return;
    }
    
    currentPos = capture.get(CV_CAP_PROP_POS_FRAMES);
    if (currentPos != noFrame) {
        std::cout << "Requesting frame " << noFrame << " but current position == " << currentPos << std::endl;
    }
    
    success = capture.read(frame_aux);
    if (!success) {
        std::cout << "Cannot get frame from video file " << std::endl;
        return;
    }
    imshow("test", frame_aux);
    
2 of 4
8

Just as BlouBlou said, when you read some high compression video format with FFMPEG, it used "key frame" technology to decode video. So set CV_CAP_PROP_POS_FRAMES property will not work as you want.

I tested 5 mpeg videos to read all frames from them. Get total frame count using long totalFrameNumber = capture.get(CV_CAP_PROP_FRAME_COUNT);

Then I read each video twice, first time not set CV_CAP_PROP_POS_FRAMES to 0, second time set it.

It did drop some frames when you set CV_CAP_PROP_POS_FRAMES to 0, about 10 frames each video. I guess because the key frame is not in the first frame of the video, so FFMPEG skip some frames to the first key frame. But some video format such as .avi won't appear such problem. I hope my real experience will save other people much time (well I spent to find this page not too long but enough).

Anyway, highly recommend not to using CV_CAP_PROP_POS_FRAMES to get a specific frame when you face mpeg format video. It is a smart choice to set CV_CAP_PROP_POS_MSEC:)

🌐
GitHub
github.com › opencv › opencv › issues › 21006
VideoCapture.get(cv::CAP_PROP_FPS) is wrong for some special video · Issue #21006 · opencv/opencv · GitHub
November 4, 2021 - System information (version) OpenCV => 4.5.0 Operating System / Platform => MacOS 12.0.1 Compiler => clang 12.0.5 Detailed description The FPS get from VideoCapture.get(cv::CAP_PROP_FPS) is wrong. The coding as following: cv::VideoCaptur...
🌐
NVIDIA Developer Forums
forums.developer.nvidia.com › robotics & edge computing › jetson systems › jetson nano
cv2.VideoCapture [gstreamer] issues - Jetson Nano - NVIDIA Developer Forums
March 3, 2021 - Hi there, I’m attempting to add a gstreamer capture and output to my python script utilising open CV but I’m struggling to find success. cap = cv2.VideoCapture('v4l2src device=“/dev/video0” ! “video/x-raw, width=640, height=480, format=(string)YUY2” ! videoconvert ! video/x-raw, format=(string)BGR ! appsink ', cv2.CAP_GSTREAMER) w = cap.get(cv2.CAP_PROP_FRAME_WIDTH) h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT) fps = cap.get(cv2.CAP_PROP_FPS) print(‘Src opened, %dx%d @ %d fps’ % (w, h, fps)) gs...