Qt + opencv (C++环境) 使用多线程 锐化视频

1 单线程的缺点 无法完全利用cpu 处理速度极慢

2 除了多线程 还有什么好方法? 暂时没想出来

3 多线程原理 

线程A:读取帧

线程B:处理显示帧

4 额外功能:通过waitKey控制播放速度

#include <condition_variable>
#include <iostream>
#include <mutex>
#include <opencv.hpp>
#include <queue>
#include <thread>
#define PATH "C:/Users/wang/Desktop/20240521/ft.mp4"
#define SPEED 15
using namespace std;
using namespace cv;
queue<Mat> frameQueue;
mutex mtx;
condition_variable condVar;
bool done = false;

void captureFrames(VideoCapture &vc)
{
    Mat frame;
    while (true) {
        vc >> frame;
        if (frame.empty()) {
            lock_guard<mutex> lock(mtx);
            done = true;
            condVar.notify_all();
            break;
        }
        lock_guard<mutex> lock(mtx);
        frameQueue.push(frame);
        condVar.notify_all();
        if (waitKey(SPEED) >= 0) {
            done = true;
            condVar.notify_all();
            break;
        }
    }
}

void processFrames(Mat kernel)
{
    while (true) {
        unique_lock<mutex> lock(mtx);
        condVar.wait(lock, [] { return !frameQueue.empty() || done; });
        if (!frameQueue.empty()) {
            Mat src = frameQueue.front();
            frameQueue.pop();
            lock.unlock();

            Mat small_src, dest;
            resize(src, small_src, Size(), 0.5, 0.5);
            imshow("src", small_src);

            cv::filter2D(small_src, dest, -1, kernel);
            cv::imshow("dest", dest);
            if (cv::waitKey(SPEED) >= 0) {
                done = true;
                condVar.notify_all();
                break;
            }
        } else if (done) {
            break;
        }
    }
}

int main()
{
    VideoCapture vc;
    if (!vc.open(PATH)) {
        cerr << "failed!" << endl;
        return -1;
    }

    Mat kernel = (Mat_<float>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);

    thread captureThread(captureFrames, ref(vc));
    thread processThread(processFrames, kernel);

    captureThread.join();
    processThread.join();

    vc.release();
    destroyAllWindows();

    return 0;
}

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值