2

I am using Ubuntu 20.04.4, and I compiled OpenCV as release mode. Whenever I read frames, it consumes quite a lot of my CPU. I tested this in other machines as well. However, using a very similar script on python, it uses much less CPU. I found this question that seems to have a similar problem as mine. Although I am using the Release version.

Also, my python seems to be using the same OpenCV version as the one I compiled: 4.5.5.

Here is the C++ test code:

#include "opencv2/opencv.hpp"

int main(){
    cv::VideoCapture vo = cv::VideoCapture(2);
    //Set fourc for better performance.
    vo.set(cv::CAP_PROP_FOURCC, cv::VideoWriter::fourcc('M','J','P','G'));
    vo.set(cv::CAP_PROP_FPS,30);
    //Setting buffersize to one will make vi.read() blocking until next frame is available.
    vo.set(cv::CAP_PROP_BUFFERSIZE,1);
    vo.set(cv::CAP_PROP_FRAME_WIDTH,1920);
    vo.set(cv::CAP_PROP_FRAME_HEIGHT,1080); 
    cv::Mat frame;
    while (vo.isOpened())
    {
        vo.read(frame);
    }
    
}

And the python code:

import cv2

vo = cv2.VideoCapture(2)
vo.set(cv2.CAP_PROP_FPS,30)
vo.set(cv2.CAP_PROP_BUFFERSIZE,1)
vo.set(cv2.CAP_PROP_FRAME_WIDTH,1920)
vo.set(cv2.CAP_PROP_FRAME_HEIGHT,1080)

while(vo.isOpened()):
    ret, frame = vo.read()

The python script consumes around 10% of my CPU while the C++ consumes around 30%. I work in an environment where CPU resource is critical. I'd like to know if there is any way to decrease this usage. Am I missing something?

5
  • 5
    Why are you using different settings in C++ and in Python? Commented Mar 31, 2022 at 20:19
  • 2
    cv2.CAP_PROP_FPS in python is 60 while in C++ is 30 Commented Mar 31, 2022 at 20:24
  • oops! Sorry, that was a typo. Commented Apr 1, 2022 at 11:09
  • 1
    both codes still differ in the setting of a fourcc. -- use getBuildInformation() from both languages and compare/diff both outputs. Commented Apr 1, 2022 at 11:52
  • @BarzanHayati then Python's CPU usage should higher. Commented Feb 9, 2024 at 3:25

1 Answer 1

2

Thanks for @ChristophRackwitz. Apparently, it was the fourcc configuration that was causing the high CPU usage. Using a resolution of 1920x1080 will cramp FPS to 5 using the default YUYV encoding. This is likely why I got lower CPU usage using python. enter image description here

If I set the fourcc on python to MJPG the CPU usage spikes.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.