QTimer和OpenCV运行缓慢

3
我正在编写一段代码,使用QTimer触发调用opencv videoCapture读取视频帧。我通常会读取大量的视频,所以想知道是否有其他方法来加速这个过程。
以下是使用QTimer的代码示例:
timer = new  QTimer();
timer->setTimerType(Qt::PreciseTimer);
connect(timer, SIGNAL(timeout()), this, SLOT(read_shape_params()));

//in a loop stop timer and setup the next video stream then start

void next(){

  timer->stop();

   stream = new video_stream_reader();
   stream->setColorGray(grayImage);
   stream->set_begin_end(begin_at,end_at);
   stream->open(video_base_path+video_path);

   timer->start(0);
}

void shape_param_finder::read_shape_params(){
   Mat frame;
   frame = stream->read_frame();
}

Mat video_stream_reader::read_frame(){
   Mat frame;
   bool bSuccess = capture->read(frame);
   return frame;

}

我不太明白你想要实现什么,是计时器运行得太慢了吗? - GPPK
是的,确实如此。QTimer 的速度非常慢。 - Riyadh Mohammed
可能是因为您正在创建一个新的计时器对象。在循环之前创建一个即可。 - GPPK
@GPPK 我在整个循环中只使用一个 QTimer 对象 - Riyadh Mohammed
@UmNyobe 我在流对象中使用帧计数器来移动到下一帧。这个方法很有效,因为我可以通过已处理的总帧数来确定当前帧。此外,我还有一个预览选项,可以让我查看读取的帧。但是相比于观看原始视频,这个方法似乎略慢一些。 - Riyadh Mohammed
显示剩余3条评论
1个回答

1

这与QTimer关系不大。但是,

timer->start(0);

是个问题。 您的视频输入摄像头有一个每秒帧数,这意味着生成帧的时间间隔。例如,25fps表示您将在此情况下每40ms获得一帧新图像。

简短回答: 如果没有适当的硬件同步,请将计时器超时设置为1000 / 期望的fps

详细回答:

定时器使用timeout = 0会尽可能快地调度read_shape_params,这意味着性能瓶颈取决于capture->read(frame);,假设代码的其他部分(显示等)完美工作。

capture->read(frame)有3种情况:

  1. It takes more time that the resolution that time period : You can't do anything. It will be slow.
  2. It is exact same time. This is the sweet spot. This is also very unlikely.
  3. It takes less time that the resolution that time period : Should be good right? Wrong. You read the same image multiple times. Which means at best you waste cpu resource. At worst, things start to behave like in case 1 from your point of view. How is that? Let say it take 30 ms to present a frame (read and show, I assume you do it linearly).

    Read 1 : 30 ms, frame 1
    Read 2 : 30 ms, frame 1 // wasted read, the other party has not updated the frame yet
    Read 3 : 30 ms, frame 2 // your second frame has 60 ms latency, not 40 ms
    Read 4 : 30 ms, frame 3 // frame 3 has 120 ms latency, sweet spot.
    Read 5 : 30 ms, frame 3 // wasted read
    Read 6 : 30 ms, frame 4 // frame 3 has 120 ms latency, sweet spot.
    
如果您不断排队显示项目,并且显示速度很慢,那么您的感知fps将会降低。
您需要对video_stream_reader::read_frame的执行时间进行基准测试以确保。
您还需要对负责显示图像的任何代码进行基准测试。我怀疑那里存在瓶颈。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接