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;
}