Mr. C
Mr. C

Reputation: 443

change frame rate in opencv 3.4.2

I want to reduce the number of frames acquired per second in a webcam, this is the code that I'm using

#!/usr/bin/env python

import cv2

cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FPS, 10)
fps = int(cap.get(5))
print("fps:", fps)

while(cap.isOpened()):

    ret,frame = cap.read()
    if not ret:
        break

    cv2.imshow('frame', frame)

    k = cv2.waitKey(1)
    if k == 27:
        break

But it doesn't take effect, I still have 30 fps by default instead of 10 set up by cap.set(cv2.CAP_PROP_FPS, 10) . I want to reduce the frame rate because I have a hand detector which take quite a lot of time to process each frame, I can not store frames in buffer since it would detect the hand in previous positions. I could run the detector using a timer or something else but I thought changing the fps was an easier way, but it didn't work and I don't know why.

Im using Opencv 3.4.2 with Python 3.6.3 in Windows 8.1

Upvotes: 33

Views: 165823

Answers (6)

Marco Bresson
Marco Bresson

Reputation: 152

Here is a class I developed to subsample a video or a live stream.

from time import time
from typing import Union
import cv2


class Stream():
    """
    extends [cv2::VideoCapture class](https://docs.opencv.org/3.4/d8/dfe/classcv_1_1VideoCapture.html)
    for video or stream subsampling.

    Parameters
    ----------
    filename : Union[str, int]
        Open video file or image file sequence or a capturing device
        or a IP video stream for video capturing.
    target_fps : int, optional
        the target frame rate. To ensure a constant time period between
        each subsampled frames, this parameter is used to compute a
        integer denominator for the extraction frequency. For instance,
        if the original stream is 64fps and you want a 30fps stream out,
        it is going to take one frame over two giving an effective frame
        rate of 32fps.
        If None, will extract every frame of the stream.
    """

    def __init__(self, filename: Union[str, int], target_fps: int = None):
        self.stream_id = filename
        self._cap = cv2.VideoCapture(self.stream_id)
        if not self.isOpened():
            raise FileNotFoundError("Stream not found")

        self.target_fps = target_fps
        self.fps = None
        self.extract_freq = None
        self.compute_extract_frequency()
        self._frame_index = 0

    def compute_extract_frequency(self):
        """evaluate the frame rate over a period of 5 seconds"""
        self.fps = self._cap.get(cv2.CAP_PROP_FPS)
        if self.fps == 0:
            self.compute_origin_fps()

        if self.target_fps is None:
            self.extract_freq = 1
        else:
            self.extract_freq = int(self.fps / self.target_fps)

            if self.extract_freq == 0:
                raise ValueError("desired_fps is higher than half the stream frame rate")

    def compute_origin_fps(self, evaluation_period: int = 5):
        """evaluate the frame rate over a period of 5 seconds"""
        while self.isOpened():
            ret, _ = self._cap.read()
            if ret is True:
                if self._frame_index == 0:
                    start = time()

                self._frame_index += 1

                if time() - start > evaluation_period:
                    break

        self.fps = round(self._frame_index / (time() - start), 2)

    def read(self):
        """Grabs, decodes and returns the next subsampled video frame."""
        ret, frame = self._cap.read()
        if ret is True:
            self._frame_index += 1

            if self._frame_index == self.extract_freq:
                self._frame_index = 0
                return ret, frame

        return False, False

    def isOpened(self):
        """Returns true if video capturing has been initialized already."""
        return self._cap.isOpened()

    def release(self):
        """Closes video file or capturing device."""
        self._cap.release()

Usage :

stream = Stream(0, 5) # subsample your webcam from probably 30fps to 5fps
stream = Stream("filename_60fps.mp4", 10) # will take on frame over 6 from your video

while stream.isOpened():
    ret, frame = stream.read()
    if ret is True:
        do_something(frame)

Upvotes: 1

This would work for your problem

import cv2
import time

cap = cv2.VideoCapture(your video)

initial_time = time.time()
to_time = time.time()

set_fps = 25 # Set your desired frame rate

# Variables Used to Calculate FPS
prev_frame_time = 0 # Variables Used to Calculate FPS
new_frame_time = 0

while True:
    while_running = time.time() # Keep updating time with each frame

    new_time = while_running - initial_time # If time taken is 1/fps, then read a frame

    if new_time >= 1 / set_fps:
        ret, frame = cap.read()
        if ret:
            # Calculating True FPS
            new_frame_time = time.time()
            fps = 1 / (new_frame_time - prev_frame_time)
            prev_frame_time = new_frame_time
            fps = int(fps)
            fps = str(fps)
            print(fps)

            cv2.imshow('joined', frame)
            initial_time = while_running # Update the initial time with current time

        else:
            total_time_of_video = while_running - to_time # To get the total time of the video
            print(total_time_of_video)
            break

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

cap.release()
cv2.destroyAllWindows()

Upvotes: -1

icapistrano
icapistrano

Reputation: 71

As Josh stated, changing the camera's fps on openCV highly depends if your camera supports the configuration you are trying to set.

I managed to change my camera's fps for openCV in Ubuntu 18.04 LTS by:

  1. Install v4l2 with "sudo apt-get install v4l-utils"

  2. Run command "v4l2-ctl --list-formats-ext" to display supported video formats including frames sizes and intervals. Results from running v4l2-ctl --list-formats-ext

  3. In my python script:

import cv2

cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')) # depends on fourcc available camera
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
cap.set(cv2.CAP_PROP_FPS, 5)

Upvotes: 7

Josh
Josh

Reputation: 2869

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.

Upvotes: 45

Jeff Blumenthal
Jeff Blumenthal

Reputation: 472

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

Upvotes: 7

Igor Zavistovich
Igor Zavistovich

Reputation: 61

The property CV_CAP_PROP_FPS only works on videos as far. If you use the follow command:

fps = cap.get(cv2.CAP_PROP_FPS)

It is returned zero. If you want to reduce frames per seconds, then you can increase a parameter of waitkey(). For example:

k = cv2.waitKey(100)

Upvotes: 2

Related Questions