解决C++ opencv 加入图像分析算法后,播放rtsp流延迟问题

2020.12.29 更新另一种方法

一般的海康摄像头是25fps,opencv在while循环中取流播放的话,完全没有问题。但是,如果加入一些目标检测等等图像操作会增加处理时间,由于硬件水平的限制,可能就达不到25fps了,这样就会堆积一部分帧,导致了延迟和花屏的现象。

解决办法:我们自己定义一个缓冲区(用vector模拟),由两个线程取维护它。read线程每次从缓冲区中取最新的帧,write线程每次取流将帧压入缓冲区。但是缓冲区数据入的速度大于出的速度,这样就需要清一下,清的时候不能全清也不能不清,隔帧抽取清理,保证画面的顺序。上代码 :

 

#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <thread>
#include <queue>
#include <chrono>
#include <unistd.h>
#include <X11/Xlib.h>

using namespace cv;
using namespace std;
using namespace std::chrono; // calc fps

std::mutex mtx;
vector<Mat> frame_buffer;

void frame_write(){
    cout << "this is write" << endl;
    Mat input, blob;
    VideoCapture capture;
    capture.open(0);
    if(capture.isOpened())
    {
        cout << "Capture is opened" << endl;
        for(;;)
        {
            capture >> input;
            if(input.empty())
                continue;
            mtx.lock();
            if(frame_buffer.size() < 100){
                frame_buffer.push_back(input);
                if (frame_buffer.size() > 10){ // 隔帧抽取一半删除
                    auto iter = frame_buffer.begin();
                    for(int inde = 0; inde < frame_buffer.size()/2 ; inde++)
                        frame_buffer.erase(iter++);
                }
            }
            else{
                cout << "thread ==============> after read stop, frame_buffer.size() > 100 , write stop";
                return;
            }
            mtx.unlock();
        }
    } else{
        cout << "open camera failed" << endl;
    }
}
void frame_read(){
    cout << "this is read" << endl;
    Mat frame;
    while(true){
        if (!frame_buffer.empty()){
            frame = frame_buffer.front();
            /// 在这里加上目标检测算法
            /*
             *
             */
            imshow("Thread Sample", frame);
            if(waitKey(10) == 27) // ’q‘ ASCII == 113
                break;
        }
    }
    cout << "thread ==============> read stop" <<endl;
}

int main(int argc, char** argv)
{
    XInitThreads();
    std::thread tw(frame_write); // pass by value
    std::thread tr(frame_read); // pass by value

    tw.detach();
    tr.join();

    return 0;
}

20200613重新修改了代码相比上次新增了一个互斥锁,但是还有个隐患,至今没有找到原因

what():  OpenCV(4.2.0) ../modules/core/src/array.cpp:2395: error: (-27:Null pointer) The matrix has NULL data pointer in function 'cvGetMat'

程序运行一段时间后还是会崩溃,经过vector后出现了空指针

参考darknet的官方代码,换了一种实现思路采取两个线程异步收发的思路,详见代码注释。

demo如下:

#include <iostream>
#include <thread>
#include <queue>
#include <chrono>
#include <atomic>
#include <unistd.h>
#include <condition_variable>

using namespace std;
using namespace std::chrono;
 

template<typename T>
class send_receive_one_object {
    std::atomic<T *> a_ptr;
    condition_variable cv_;
    mutex lock_;
public:

    void send(T const& _obj) {
        T *new_ptr = new T;
        *new_ptr = _obj;
        std::unique_ptr<T> old_ptr(a_ptr.exchange(new_ptr));
        cv_.notify_one();
    }

    T receive() {
        std::unique_ptr<T> ptr;
        do {
            std::unique_lock<mutex> l(lock_);
            cv_.wait(l, [&]{return a_ptr != NULL;});
            ptr.reset(a_ptr.exchange(NULL));
        } while (!ptr);
        T obj = *ptr;
        return obj;
    }
    send_receive_one_object() : a_ptr(NULL)
    {
        cout << "================> init send_receive_one_object" << endl;
    }
};

struct Job{
    int id;
}; // 收发数据结构体,可以写视频帧或者其他有用的数据

const bool sync_ = true;
static send_receive_one_object<Job> read_write;

void frame_write(){
    cout << "this is frame_write !!!" << endl;
    sleep(3);
    Job jj;
    int cnt = 30;
    while(cnt --){
        jj.id = 30-cnt;
        read_write.send(jj);
        usleep(10000); // 模拟取流30帧,并设置时间间隔
    }
}

void frame_read(){
    cout << "this is frame_read !!!" << endl;
    Job jj;
    int cnt = 200;
    while(cnt --){
        jj = read_write.receive();
        cout << jj.id << endl;
        usleep(30000); // 模拟算法处理速度是取流速度的1/3
    }
}

int main(int argc, char** argv)
{
    std::thread tw(frame_write);
    std::thread tr(frame_read);
 
    tw.join();
    tr.join();
 
    return 0;
}

 

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值