You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
BOE_FOG_DETECT/AlgorithmModule/src/ImageStorage.cpp

86 lines
2.1 KiB

/*
* @Author: xiewenji 527774126@qq.com
* @Date: 2025-09-11 15:32:52
* @LastEditors: xiewenji 527774126@qq.com
* @LastEditTime: 2025-09-16 09:40:36
* @FilePath: /BOE_FOG_Detect/AlgorithmModule/src/ImageStorage.cpp
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
#include "ImageStorage.h"
#include <iostream>
#include <opencv2/opencv.hpp>
ImageStorage *ImageStorage::instance = nullptr;
ImageStorage::ImageStorage() : stopFlag(false)
{
// 启动存储线程
storageThread = std::thread(&ImageStorage::storeImages, this);
}
ImageStorage::~ImageStorage()
{
stop(); // 在销毁时确保线程被正确停止
}
// 获取单例实例的静态方法
ImageStorage *ImageStorage::getInstance()
{
if (instance == nullptr)
{
instance = new ImageStorage(); // 如果实例为空,则创建新实例
}
return instance;
}
void ImageStorage::storeImages()
{
while (!stopFlag)
{
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Sleep for 100 milliseconds
std::unique_lock<std::mutex> lock(queueMutex);
cv.wait(lock, [this]()
{ return !imageQueue.empty() || stopFlag; });
if (stopFlag && imageQueue.empty())
break;
auto item = imageQueue.front();
imageQueue.pop();
lock.unlock();
cv::Mat temimg = item.first;
if (!temimg.empty())
{
cv::imwrite(item.second, item.first); // 保存图片到文件
// std::cout << "Image saved to: " << item.second << std::endl;
}
}
}
int ImageStorage::addImage(const std::string &path, const cv::Mat &image, bool badd)
{
std::lock_guard<std::mutex> lock(queueMutex);
if (imageQueue.size() > 1000 && !badd)
{
std::cout << "Queue has more than 10 items, not adding new images." << std::endl;
return 1;
}
else
{
imageQueue.push({image, path});
cv.notify_one(); // 通知存储线程处理新任务
}
return 0;
}
void ImageStorage::stop()
{
stopFlag = true;
cv.notify_one(); // 通知存储线程停止
if (storageThread.joinable())
{
storageThread.join(); // 等待线程退出
}
}