#include <opencv2/opencv.hpp>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <iostream>
#include <filesystem>
#include <chrono>
using namespace cv;
using namespace std;
std::atomic<bool> processingComplete(false);
std::atomic<int> frameCount(0);
std::queue<Mat> frameQueue;
std::mutex queueMutex;
std::condition_variable queueCondVar;
class ThreadPool {
public:
ThreadPool(size_t numThreads) {
for (size_t i = 0; i < numThreads; ++i) {
workers.emplace_back([this] {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(this->queueMutex);
this->condVar.wait(lock, [this] { return this->stop || !this->tasks.empty(); });
if (this->stop && this->tasks.empty()) return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
});
}
}
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queueMutex);
stop = true;
}
condVar.notify_all();
for (std::thread& worker : workers) {
worker.join();
}
}
template <class F>
void enqueue(F&& f) {
{
std::unique_lock<std::mutex> lock(queueMutex);
tasks.push(std::forward<F>(f));
}
condVar.notify_one();
}
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex queueMutex;
std::condition_variable condVar;
bool stop = false;
};
void processImage(const string& inputPath) {
VideoCapture cap(inputPath);
if (!cap.isOpened()) {
cerr << "Error: Unable to open the video file!" << endl;
return;
}
int width = static_cast<int>(cap.get(CAP_PROP_FRAME_WIDTH));
int height = static_cast<int>(cap.get(CAP_PROP_FRAME_HEIGHT));
while (true) {
Mat frame;
{
bool ret = cap.read(frame);
if (!ret) break;
Mat resizedFrame;
resize(frame, resizedFrame, Size(width * 2, height * 2), 0, 0, INTER_CUBIC);
{
std::lock_guard<std::mutex> lock(queueMutex);
frameQueue.push(resizedFrame);
}
queueCondVar.notify_one();
}
}
processingComplete = true;
queueCondVar.notify_all();
cap.release();
}
void displayImage() {
int frameIdx = 0;
double startTime = (double)getTickCount();
while (true) {
Mat frame;
{
std::unique_lock<std::mutex> lock(queueMutex);
queueCondVar.wait(lock, [] { return !frameQueue.empty() || processingComplete; });
if (frameQueue.empty() && processingComplete) break;
frame = frameQueue.front();
frameQueue.pop();
}
imshow("Processed Image", frame);
frameIdx++;
double elapsedTime = ((double)getTickCount() - startTime) / getTickFrequency();
cout << "Frame rate: " << frameIdx / elapsedTime << " FPS" << endl;
if (waitKey(1) == 'q') break;
}
destroyAllWindows();
}
int main(int argc, char** argv) {
string inputPath = "D:\\BaiduNetdiskDownload\\Reset_2022_E01_4K.mp4";
ThreadPool pool(8);
pool.enqueue([&] { processImage(inputPath); });
pool.enqueue(displayImage);
return 0;
}