#include "ImageProcessingWorker.h" #include "PointCloudImageUtils.h" #include "VrLog.h" #include #include "VrTimeUtils.h" ImageProcessingWorker::ImageProcessingWorker(QObject *parent) : QObject(parent) , m_stopped(false) , m_processing(false) , m_hasNewTask(false) { // 启动工作线程 m_workerThread = std::thread(&ImageProcessingWorker::workerThreadFunction, this); LOG_DEBUG("ImageProcessingWorker created with std::thread\n"); } ImageProcessingWorker::~ImageProcessingWorker() { stop(); // 等待线程结束 if (m_workerThread.joinable()) { m_workerThread.join(); } LOG_DEBUG("ImageProcessingWorker destroyed\n"); } void ImageProcessingWorker::requestImageGeneration(const std::vector>& scanLines) { if (m_stopped.load() || scanLines.empty()) { return; } // 如果正在处理,直接拒绝新请求 if (m_processing.load()) { LOG_DEBUG("Image processing busy, ignoring new request\n"); return; } // 设置新任务 { std::lock_guard lock(m_dataMutex); m_currentTask = scanLines; m_hasNewTask = true; } // 唤醒工作线程 m_condition.notify_one(); } void ImageProcessingWorker::stop() { m_stopped.store(true); // 唤醒可能在等待的线程 m_condition.notify_all(); LOG_DEBUG("ImageProcessingWorker stop requested\n"); } bool ImageProcessingWorker::isProcessing() const { return m_processing.load(); } void ImageProcessingWorker::workerThreadFunction() { LOG_INFO("ImageProcessingWorker thread started\n"); while (!m_stopped.load()) { std::vector> scanLines; bool hasTask = false; // 等待任务或停止信号 { std::unique_lock lock(m_dataMutex); // 等待新任务或停止信号 m_condition.wait_for(lock, std::chrono::milliseconds(100), [this] { return m_hasNewTask || m_stopped.load(); }); if (m_hasNewTask) { scanLines = std::move(m_currentTask); m_hasNewTask = false; hasTask = true; } } // 处理任务 if (hasTask && !m_stopped.load()) { processImageGeneration(scanLines); } } LOG_INFO("ImageProcessingWorker thread finished\n"); } void ImageProcessingWorker::processImageGeneration(const std::vector>& scanLines) { m_processing.store(true); try { CVrTimeUtils oTime; std::vector> emptyResults; // 空的检测结果 QImage image = PointCloudImageUtils::GeneratePointCloudImage(scanLines, emptyResults, 800, 600); if (!image.isNull()) { LOG_DEBUG("ImageProcessingWorker processImageGeneration, image size: %dx%d time: %.fms\n", image.width(), image.height(), oTime.GetElapsedTimeInMilliSec()); emit imageGenerated(image); } else { LOG_WARNING("Failed to generate image in worker thread\n"); } } catch (const std::exception& e) { LOG_ERROR("Error in worker thread image processing: %s\n", e.what()); } catch (...) { LOG_ERROR("Unknown error in worker thread image processing\n"); } m_processing.store(false); }