Files
VisionGuide/source/YoloPanel.cpp
T

719 lines
28 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// YoloPanel.cpp
#include "YoloPanel.h"
#include "ui_MainWindow.h"
#include "AppSettings.h"
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "CameraManager.h"
#include <QApplication>
#include <QCoreApplication>
#include <QDateTime>
#include <QDir>
#include <QEventLoop>
#include <QFile>
#include <QPainter>
#include <QElapsedTimer>
#include <QFileInfo>
#include <QFileDialog>
#include <QFontMetrics>
#include <QHeaderView>
#include <QPixmap>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QAbstractItemView>
#include <QThread>
#include <QScopeGuard>
#include <QTimer>
#include <limits>
#include <algorithm>
#include <cmath>
namespace {
QString grooveDatasetOriginalDir()
{
const QDir cwd(QDir::currentPath());
const QString cwdRoot = cwd.absoluteFilePath(QStringLiteral("groove_yolov8"));
if (QDir(cwdRoot).exists()) {
return QDir::cleanPath(QDir(cwdRoot).absoluteFilePath(
QStringLiteral("00_original_images")));
}
const QDir appDir(QCoreApplication::applicationDirPath());
return QDir::cleanPath(appDir.absoluteFilePath(
QStringLiteral("../../groove_yolov8/00_original_images")));
}
QString groovePoseImageDir()
{
return QDir::cleanPath(QStringLiteral(
"D:/Qt/firstdemo/firstdemo/x64/Debug/export/images_groove_pose"));
}
QString uniqueBatchBaseName(const QDir& outputDir)
{
const QString stamp = QDateTime::currentDateTime().toString(
QStringLiteral("yyyyMMdd_HHmmss_zzz"));
QString base = QStringLiteral("scene_%1").arg(stamp);
int suffix = 1;
auto batchExists = [&outputDir](const QString& candidate) {
QStringList filters;
filters << candidate + QStringLiteral("_exp*_left.png")
<< candidate + QStringLiteral("_exp*_right.png")
<< candidate + QStringLiteral("_left.png")
<< candidate + QStringLiteral("_right.png");
return !outputDir.entryList(filters, QDir::Files).isEmpty();
};
while (batchExists(base)) {
base = QStringLiteral("scene_%1_%2")
.arg(stamp)
.arg(suffix++, 2, 10, QLatin1Char('0'));
}
return base;
}
bool saveStereoPair(const QImage& leftImage, const QImage& rightImage,
const QString& leftPath, const QString& rightPath)
{
const bool leftSaved = leftImage.save(leftPath, "PNG");
const bool rightSaved = rightImage.save(rightPath, "PNG");
if (!leftSaved || !rightSaved) {
QFile::remove(leftPath);
QFile::remove(rightPath);
return false;
}
return true;
}
QString defaultGrooveModelPath()
{
const QString relativePath = QStringLiteral("Yolo/groove_best.onnx");
const QDir cwd(QDir::currentPath());
const QDir appDir(QCoreApplication::applicationDirPath());
const QStringList candidates = {
cwd.absoluteFilePath(relativePath),
appDir.absoluteFilePath(relativePath),
appDir.absoluteFilePath(QStringLiteral("../../") + relativePath),
appDir.absoluteFilePath(QStringLiteral("../") + relativePath)
};
for (const QString& candidate : candidates) {
if (QFileInfo::exists(candidate))
return QDir::cleanPath(candidate);
}
return {};
}
QString grooveStateText(int classId)
{
return classId == 0
? QString::fromUtf8("空凹槽")
: QString::fromUtf8("已占用");
}
QColor grooveColor(int classId)
{
return classId == 0 ? QColor(22, 119, 255) : QColor(245, 34, 45);
}
} // namespace
YoloPanel::YoloPanel(Ui::MainWindowClass& u, YoloDetector* det,
CameraManager* cameraManager, QObject* parent)
: QObject(parent), ui(u), m_det(det), m_cameraManager(cameraManager)
{
connect(ui.btnLoadYoloModel, &QPushButton::clicked, this, &YoloPanel::onLoadModel);
connect(ui.btnRunYolo, &QPushButton::clicked, this, &YoloPanel::onRunYolo);
connect(ui.btnCaptureStereoDataset, &QPushButton::clicked,
this, &YoloPanel::onCaptureStereoDataset);
connect(ui.btnCaptureStereoPair, &QPushButton::clicked,
this, &YoloPanel::onCaptureStereoPair);
connect(ui.btnAutoCropROI, &QPushButton::clicked, this, &YoloPanel::onAutoCropROI);
connect(ui.btnClearYoloResult, &QPushButton::clicked, this, &YoloPanel::onClearResult);
connect(ui.btnClearROI, &QPushButton::clicked, this, &YoloPanel::onClearROI);
connect(m_det, &YoloDetector::modelLoaded, this, &YoloPanel::onModelLoaded);
connect(m_det, &YoloDetector::errorOccurred, this, &YoloPanel::onYoloError);
if (m_cameraManager) {
connect(m_cameraManager, &CameraManager::cameraConnected,
this, [this](CameraManager::CamIndex) { updateStates(); });
connect(m_cameraManager, &CameraManager::cameraDisconnected,
this, [this](CameraManager::CamIndex) { updateStates(); });
}
updateStates();
}
void YoloPanel::setCapturedFrame(const QImage& img) { m_frame = img; updateStates(); }
void YoloPanel::setROI(const QRect& r) { m_roi = r; emit roiChanged(r); updateStates(); }
void YoloPanel::clearState()
{
m_results.clear(); m_roi = QRect();
ui.editCountGold->clear(); ui.editCountNonGold->clear(); ui.editDetectTime->clear();
ui.labelROICoords->setText(QString::fromUtf8("ROI: 未选取"));
updateStates();
}
void YoloPanel::updateStates()
{
bool hasModel = m_det->isLoaded();
bool hasFrame = !m_frame.isNull();
const bool leftCameraReady = m_cameraManager &&
m_cameraManager->isConnected(CameraManager::LEFT);
ui.btnRunYolo->setEnabled(hasModel && hasFrame);
ui.btnAutoCropROI->setEnabled(hasModel && hasFrame);
ui.btnClearROI->setEnabled(m_roi.isValid());
const bool stereoReady = m_cameraManager &&
m_cameraManager->isConnected(CameraManager::LEFT) &&
m_cameraManager->isConnected(CameraManager::RIGHT);
ui.btnCaptureStereoDataset->setEnabled(stereoReady);
ui.btnCaptureStereoPair->setEnabled(stereoReady);
if (hasModel) {
ui.labelModelStatus->setText(QString::fromUtf8("● 模型已加载: %1 (%2类)")
.arg(QFileInfo(m_det->modelPath()).fileName()).arg(m_det->numClasses()));
ui.labelModelStatus->setStyleSheet("color:#00cc66;");
} else {
ui.labelModelStatus->setText(QString::fromUtf8("● 模型未加载"));
ui.labelModelStatus->setStyleSheet("color:gray;");
}
}
void YoloPanel::onCaptureStereoDataset()
{
if(m_busy||m_resourceBlocked)return;
auto release=qScopeGuard([this]{m_busy=false;updateStates();emit busyChanged(false);});
m_busy=true;emit busyChanged(true);
if (!m_cameraManager ||
!m_cameraManager->isConnected(CameraManager::LEFT) ||
!m_cameraManager->isConnected(CameraManager::RIGHT)) {
emit logMessage(QString::fromUtf8(
"[凹槽数据集] 双目采集失败:请先连接左右相机。"));
updateStates();
return;
}
const QString outputPath = grooveDatasetOriginalDir();
if (!QDir().mkpath(outputPath)) {
emit logMessage(QString::fromUtf8(
"[凹槽数据集] 无法创建保存目录:%1").arg(outputPath));
return;
}
const QDir outputDir(outputPath);
const QString batchBaseName = uniqueBatchBaseName(outputDir);
const QVector<int> exposureValuesUs = {
20000, 30000, 40000, 50000, 60000
};
double originalLeftExposure = 0.0;
double originalRightExposure = 0.0;
const bool hasOriginalLeftExposure = m_cameraManager->getExposureTime(
CameraManager::LEFT, originalLeftExposure);
const bool hasOriginalRightExposure = m_cameraManager->getExposureTime(
CameraManager::RIGHT, originalRightExposure);
const bool leftWasPreviewing = m_cameraManager->isPreviewing(CameraManager::LEFT);
const bool rightWasPreviewing = m_cameraManager->isPreviewing(CameraManager::RIGHT);
if (leftWasPreviewing) m_cameraManager->stopPreview(CameraManager::LEFT);
if (rightWasPreviewing) m_cameraManager->stopPreview(CameraManager::RIGHT);
const QString originalButtonText = ui.btnCaptureStereoDataset->text();
ui.btnCaptureStereoDataset->setEnabled(false);
QApplication::setOverrideCursor(Qt::WaitCursor);
emit logMessage(QString::fromUtf8(
"[凹槽数据集] 开始多曝光双目采集:20000~60000 μs,步长10000 μs;"
"共5组。采集期间请保持料盘静止。"));
int savedGroupCount = 0;
QImage lastLeftImage;
QStringList failedExposures;
for (int index = 0; index < exposureValuesUs.size(); ++index) {
const int exposureUs = exposureValuesUs[index];
ui.btnCaptureStereoDataset->setText(
QString::fromUtf8("采集中 %1/5(%2 μs)")
.arg(index + 1)
.arg(exposureUs));
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
const bool leftExposureSet = m_cameraManager->setExposureTime(
CameraManager::LEFT, exposureUs);
const bool rightExposureSet = m_cameraManager->setExposureTime(
CameraManager::RIGHT, exposureUs);
if (!leftExposureSet || !rightExposureSet) {
failedExposures << QString::number(exposureUs);
emit logMessage(QString::fromUtf8(
"[凹槽数据集] %1 μs曝光设置失败:LEFT=%2,RIGHT=%3;跳过本组。")
.arg(exposureUs)
.arg(leftExposureSet ? QStringLiteral("成功") : QStringLiteral("失败"))
.arg(rightExposureSet ? QStringLiteral("成功") : QStringLiteral("失败")));
continue;
}
// Give both cameras a short settling interval after changing exposure.
QThread::msleep(100);
const QImage leftImage = m_cameraManager->captureSingleFrame(CameraManager::LEFT);
const QImage rightImage = m_cameraManager->captureSingleFrame(CameraManager::RIGHT);
if (leftImage.isNull() || rightImage.isNull()) {
failedExposures << QString::number(exposureUs);
emit logMessage(QString::fromUtf8(
"[凹槽数据集] %1 μs采集失败:LEFT=%2,RIGHT=%3;本组不保存。")
.arg(exposureUs)
.arg(leftImage.isNull() ? QStringLiteral("失败") : QStringLiteral("成功"))
.arg(rightImage.isNull() ? QStringLiteral("失败") : QStringLiteral("成功")));
continue;
}
const QString exposureTag = QStringLiteral("_exp%1").arg(exposureUs);
const QString leftPath = outputDir.absoluteFilePath(
batchBaseName + exposureTag + QStringLiteral("_left.png"));
const QString rightPath = outputDir.absoluteFilePath(
batchBaseName + exposureTag + QStringLiteral("_right.png"));
if (!saveStereoPair(leftImage, rightImage, leftPath, rightPath)) {
failedExposures << QString::number(exposureUs);
emit logMessage(QString::fromUtf8(
"[凹槽数据集] %1 μs文件保存失败,已清理本组不完整图像。")
.arg(exposureUs));
continue;
}
lastLeftImage = leftImage;
++savedGroupCount;
emit logMessage(QString::fromUtf8(
"[凹槽数据集] %1/5保存成功:%2 μs,尺寸%3x%4")
.arg(index + 1)
.arg(exposureUs)
.arg(leftImage.width())
.arg(leftImage.height()));
}
if (hasOriginalLeftExposure)
m_cameraManager->setExposureTime(CameraManager::LEFT, originalLeftExposure);
if (hasOriginalRightExposure)
m_cameraManager->setExposureTime(CameraManager::RIGHT, originalRightExposure);
if (leftWasPreviewing) m_cameraManager->startPreview(CameraManager::LEFT);
if (rightWasPreviewing) m_cameraManager->startPreview(CameraManager::RIGHT);
QApplication::restoreOverrideCursor();
ui.btnCaptureStereoDataset->setText(originalButtonText);
updateStates();
if (!lastLeftImage.isNull()) setCapturedFrame(lastLeftImage);
const QString failureText = failedExposures.isEmpty()
? QString::fromUtf8("无")
: failedExposures.join(QStringLiteral(", ")) + QStringLiteral(" μs");
emit logMessage(QString::fromUtf8(
"[凹槽数据集] 多曝光批次完成:成功%1/5组,失败曝光=%2\n 批次=%3\n 目录=%4")
.arg(savedGroupCount)
.arg(failureText)
.arg(batchBaseName)
.arg(outputPath));
}
void YoloPanel::onCaptureStereoPair()
{
if(m_busy||m_resourceBlocked)return;
auto release=qScopeGuard([this]{m_busy=false;updateStates();emit busyChanged(false);});
m_busy=true;emit busyChanged(true);
if (!m_cameraManager ||
!m_cameraManager->isConnected(CameraManager::LEFT) ||
!m_cameraManager->isConnected(CameraManager::RIGHT)) {
emit logMessage(QString::fromUtf8(
"[凹槽位姿图像] 双目采集失败:请先连接左右相机。"));
updateStates();
return;
}
const QString outputPath = groovePoseImageDir();
if (!QDir().mkpath(outputPath)) {
emit logMessage(QString::fromUtf8(
"[凹槽位姿图像] 无法创建保存目录:%1").arg(outputPath));
return;
}
const QDir outputDir(outputPath);
const QString pairBaseName = uniqueBatchBaseName(outputDir);
const QString leftPath = outputDir.absoluteFilePath(
pairBaseName + QStringLiteral("_left.png"));
const QString rightPath = outputDir.absoluteFilePath(
pairBaseName + QStringLiteral("_right.png"));
const bool leftWasPreviewing = m_cameraManager->isPreviewing(CameraManager::LEFT);
const bool rightWasPreviewing = m_cameraManager->isPreviewing(CameraManager::RIGHT);
if (leftWasPreviewing) m_cameraManager->stopPreview(CameraManager::LEFT);
if (rightWasPreviewing) m_cameraManager->stopPreview(CameraManager::RIGHT);
const QString originalButtonText = ui.btnCaptureStereoPair->text();
ui.btnCaptureStereoPair->setEnabled(false);
ui.btnCaptureStereoDataset->setEnabled(false);
ui.btnCaptureStereoPair->setText(QString::fromUtf8("双目采集中..."));
QApplication::setOverrideCursor(Qt::WaitCursor);
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
// Keep both cameras at their current exposure and capture one original pair.
const QImage leftImage = m_cameraManager->captureSingleFrame(CameraManager::LEFT);
const QImage rightImage = m_cameraManager->captureSingleFrame(CameraManager::RIGHT);
const bool captureSucceeded = !leftImage.isNull() && !rightImage.isNull();
const bool saveSucceeded = captureSucceeded &&
saveStereoPair(leftImage, rightImage, leftPath, rightPath);
if (leftWasPreviewing) m_cameraManager->startPreview(CameraManager::LEFT);
if (rightWasPreviewing) m_cameraManager->startPreview(CameraManager::RIGHT);
QApplication::restoreOverrideCursor();
ui.btnCaptureStereoPair->setText(originalButtonText);
updateStates();
if (!captureSucceeded) {
emit logMessage(QString::fromUtf8(
"[凹槽位姿图像] 双目采集失败:LEFT=%1,RIGHT=%2;未保存图像。")
.arg(leftImage.isNull() ? QStringLiteral("失败") : QStringLiteral("成功"))
.arg(rightImage.isNull() ? QStringLiteral("失败") : QStringLiteral("成功")));
return;
}
if (!saveSucceeded) {
emit logMessage(QString::fromUtf8(
"[凹槽位姿图像] 文件保存失败,已清理不完整图像:%1")
.arg(outputPath));
return;
}
setCapturedFrame(leftImage);
emit logMessage(QString::fromUtf8(
"[凹槽位姿图像] 双目单次采集保存成功(保持当前曝光,不进行多重曝光):"
"%1x%2\n 左图=%3\n 右图=%4")
.arg(leftImage.width())
.arg(leftImage.height())
.arg(leftPath)
.arg(rightPath));
}
void YoloPanel::onLoadModel()
{
QString p = AppSettings::instance().openFile(
qobject_cast<QWidget*>(parent()), AppSettings::K_YoloModel,
QString::fromUtf8("选择 YOLO ONNX 模型"),
QString::fromUtf8("ONNX 模型 (*.onnx);;All Files (*)"));
if (p.isEmpty()) return;
ui.labelModelPath->setText(p);
m_det->loadModel(p);
}
void YoloPanel::autoLoadGrooveModel()
{
const QString modelPath = defaultGrooveModelPath();
if (modelPath.isEmpty()) {
ui.labelGrooveModelPath->setText(QString::fromUtf8(
"凹槽模型路径:未找到 Yolo/groove_best.onnx"));
emit logMessage(QString::fromUtf8(
"[凹槽占位] 未找到 groove_best.onnx;请将模型放到 Yolo 目录或手动加载。"));
updateStates();
return;
}
loadGrooveModel(modelPath);
}
bool YoloPanel::loadGrooveModel(const QString& modelPath)
{
if (!m_grooveDet->loadModel(modelPath)) {
m_grooveModelValid = false;
emit logMessage(QString::fromUtf8("[凹槽占位错误] ") +
m_grooveDet->lastError());
updateStates();
return false;
}
m_grooveModelValid = true;
ui.labelGrooveModelPath->setText(modelPath);
emit logMessage(QString::fromUtf8(
"[凹槽占位] 独立模型加载成功:%1;输入=%2×%3;类别=empty_groove、occupied_groove。")
.arg(QFileInfo(modelPath).fileName())
.arg(m_grooveDet->inputWidth())
.arg(m_grooveDet->inputHeight()));
updateStates();
return true;
}
void YoloPanel::onLoadGrooveModel()
{
const QString fallback = defaultGrooveModelPath();
const QString modelPath = QFileDialog::getOpenFileName(
qobject_cast<QWidget*>(parent()),
QString::fromUtf8("选择凹槽占位识别 ONNX 模型"),
fallback.isEmpty() ? QDir::currentPath() : QFileInfo(fallback).absolutePath(),
QString::fromUtf8("ONNX 模型 (*.onnx);;All Files (*)"));
if (modelPath.isEmpty())
return;
loadGrooveModel(modelPath);
}
void YoloPanel::onModelLoaded(const QString& p) {
emit logMessage(QString::fromUtf8("模型加载成功: %1 (%2类)")
.arg(QFileInfo(p).fileName()).arg(m_det->numClasses()));
updateStates();
}
void YoloPanel::onYoloError(const QString& msg) {
emit logMessage("[YOLO Error] " + msg);
updateStates();
}
void YoloPanel::onRunYolo()
{
if (m_frame.isNull() || !m_det->isLoaded()) return;
emit logMessage(QString::fromUtf8("正在执行YOLO检测..."));
int filterClass = -1;
if (ui.radioDetectGold->isChecked()) filterClass = 1;
if (ui.radioDetectNonGold->isChecked()) filterClass = 2;
int origW = m_frame.width(), origH = m_frame.height();
QImage img640 = m_frame.scaled(640, 640, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
QElapsedTimer timer; timer.start();
m_results = m_det->detect(img640, m_confThresh, m_nmsThresh, filterClass);
qint64 ms = timer.elapsed();
double sx = double(origW)/640.0, sy = double(origH)/640.0;
int gold=0, nonGold=0;
for (auto& r : m_results) { if(r.classId==1) ++gold; else if(r.classId==2) ++nonGold; }
ui.editCountGold->setText(QString::number(gold));
ui.editCountNonGold->setText(QString::number(nonGold));
ui.editDetectTime->setText(QString::number(ms));
// 绘制标注图
QImage annotated = m_frame.copy();
QPainter painter(&annotated);
painter.setRenderHint(QPainter::Antialiasing);
QVector<QColor> colors = {QColor(0,0,255), QColor(255,0,0), QColor(0,255,0)};
for (const auto& r : m_results) {
QRectF box(r.box.x()*sx, r.box.y()*sy, r.box.width()*sx, r.box.height()*sy);
QColor c = colors[r.classId % colors.size()];
painter.setPen(QPen(c, 3));
painter.drawRect(box);
QString label = r.label + " (" + QString::number(r.conf,'f',3) + ")";
QFont f = painter.font(); f.setBold(true); f.setPointSize(14); painter.setFont(f);
QRectF bg(box.topLeft()-QPointF(0,22), QSizeF(label.length()*12, 22));
painter.fillRect(bg, c);
painter.setPen(Qt::white);
painter.drawText(box.topLeft()+QPointF(2,-4), label);
}
painter.end();
emit logMessage(QString::fromUtf8("YOLO检测完成 镀金=%1 非镀金=%2 耗时=%3ms")
.arg(gold).arg(nonGold).arg(ms));
emit yoloCompleted();
}
void YoloPanel::onRunGrooveOccupancy()
{
if (!m_grooveModelValid || !m_grooveDet->isLoaded()) {
emit logMessage(QString::fromUtf8("[凹槽占位] 模型未就绪,无法执行识别。"));
return;
}
QImage sourceImage;
QString sourceName;
// Prefer a new image so the displayed occupancy reflects the current tray.
if (m_cameraManager && m_cameraManager->isConnected(CameraManager::LEFT)) {
sourceImage = m_cameraManager->captureSingleFrame(CameraManager::LEFT);
sourceName = QString::fromUtf8("左相机稳定单帧");
if (!sourceImage.isNull())
m_frame = sourceImage;
}
if (sourceImage.isNull() && !m_frame.isNull()) {
sourceImage = m_frame;
sourceName = QString::fromUtf8("当前缓存图像");
}
if (sourceImage.isNull()) {
emit logMessage(QString::fromUtf8(
"[凹槽占位] 无可用图像:请连接左相机或先采集一张图像。"));
updateStates();
return;
}
QElapsedTimer timer;
timer.start();
m_grooveResults = m_grooveDet->detect(
sourceImage, m_grooveConfThresh, m_grooveNmsThresh);
const qint64 elapsedMs = timer.elapsed();
std::sort(m_grooveResults.begin(), m_grooveResults.end(),
[](const GrooveDetectionResult& a, const GrooveDetectionResult& b) {
const QPointF ac = a.box.center();
const QPointF bc = b.box.center();
if (std::abs(ac.y() - bc.y()) > 1.0)
return ac.y() < bc.y();
return ac.x() < bc.x();
});
int emptyCount = 0;
int occupiedCount = 0;
for (const GrooveDetectionResult& result : m_grooveResults) {
if (result.classId == 0)
++emptyCount;
else if (result.classId == 1)
++occupiedCount;
}
ui.editEmptyGrooveCount->setText(QString::number(emptyCount));
ui.editOccupiedGrooveCount->setText(QString::number(occupiedCount));
ui.editGrooveDetectTime->setText(QString::number(elapsedMs));
ui.labelGrooveResultStatus->setText(QString::fromUtf8(
"识别结果:空凹槽 %1 个,已占用 %2 个,总计 %3 个;来源:%4")
.arg(emptyCount)
.arg(occupiedCount)
.arg(m_grooveResults.size())
.arg(sourceName));
ui.tableGrooveResults->setRowCount(m_grooveResults.size());
for (int i = 0; i < m_grooveResults.size(); ++i) {
const GrooveDetectionResult& result = m_grooveResults[i];
const QPointF center = result.box.center();
const QStringList values = {
QString::number(i + 1),
grooveStateText(result.classId),
QString::number(result.confidence, 'f', 3),
QString::number(center.x(), 'f', 1),
QString::number(center.y(), 'f', 1),
QStringLiteral("x=%1 y=%2 w=%3 h=%4")
.arg(result.box.x(), 0, 'f', 1)
.arg(result.box.y(), 0, 'f', 1)
.arg(result.box.width(), 0, 'f', 1)
.arg(result.box.height(), 0, 'f', 1)
};
for (int col = 0; col < values.size(); ++col) {
auto* item = new QTableWidgetItem(values[col]);
if (col == 1)
item->setForeground(grooveColor(result.classId));
item->setTextAlignment(Qt::AlignCenter);
ui.tableGrooveResults->setItem(i, col, item);
}
}
QImage annotated = sourceImage.copy();
QPainter painter(&annotated);
painter.setRenderHint(QPainter::Antialiasing);
const int penWidth = qMax(3, annotated.width() / 800);
QFont font = painter.font();
font.setBold(true);
font.setPointSize(qMax(12, annotated.width() / 90));
painter.setFont(font);
const QFontMetrics metrics(font);
for (const GrooveDetectionResult& result : m_grooveResults) {
const QColor color = grooveColor(result.classId);
painter.setPen(QPen(color, penWidth));
painter.drawRect(result.box);
const QString text = QStringLiteral("%1 %2")
.arg(grooveStateText(result.classId))
.arg(result.confidence, 0, 'f', 2);
const int textHeight = metrics.height() + 8;
const int textWidth = metrics.horizontalAdvance(text) + 12;
QRectF textRect(result.box.left(),
qMax<qreal>(0.0, result.box.top() - textHeight), textWidth, textHeight);
painter.fillRect(textRect, color);
painter.setPen(Qt::white);
painter.drawText(textRect, Qt::AlignCenter, text);
}
painter.end();
emit logMessage(QString::fromUtf8(
"[凹槽占位] 检测完成:空凹槽=%1,已占用=%2,总数=%3,耗时=%4ms,来源=%5,输入=%6×%7。")
.arg(emptyCount)
.arg(occupiedCount)
.arg(m_grooveResults.size())
.arg(elapsedMs)
.arg(sourceName)
.arg(sourceImage.width())
.arg(sourceImage.height()));
}
void YoloPanel::onAutoCropROI()
{
if (m_frame.isNull() || !m_det->isLoaded()) return;
if (m_results.isEmpty()) { onRunYolo(); if (m_results.isEmpty()) return; }
int bestIdx = 0; float bestConf = 0;
for (int i = 0; i < m_results.size(); ++i)
if (m_results[i].conf > bestConf) { bestConf = m_results[i].conf; bestIdx = i; }
double sx = double(m_frame.width())/640.0, sy = double(m_frame.height())/640.0;
QRectF b = m_results[bestIdx].box;
QRectF box(b.x()*sx, b.y()*sy, b.width()*sx, b.height()*sy);
double pw = box.width()*0.10, ph = box.height()*0.10;
box.adjust(-pw, -ph, pw, ph);
int x1 = qBound(0, int(box.x()), m_frame.width());
int y1 = qBound(0, int(box.y()), m_frame.height());
int w = qBound(10, int(box.width()), m_frame.width()-x1);
int h = qBound(10, int(box.height()), m_frame.height()-y1);
m_roi = QRect(x1, y1, w, h);
ui.labelROICoords->setText(QString::fromUtf8("ROI(YOLO): x=%1 y=%2 w=%3 h=%4")
.arg(x1).arg(y1).arg(w).arg(h));
emit roiChanged(m_roi);
updateStates();
}
void YoloPanel::onClearROI()
{
m_roi = QRect();
ui.labelROICoords->setText(QString::fromUtf8("ROI: 未选取"));
emit roiChanged(m_roi);
emit logMessage(QString::fromUtf8("ROI已清除"));
updateStates();
}
void YoloPanel::onClearResult()
{
ui.editCountGold->clear(); ui.editCountNonGold->clear(); ui.editDetectTime->clear();
m_results.clear();
emit logMessage(QString::fromUtf8("YOLO检测结果已清空"));
}
void YoloPanel::clearGrooveResults()
{
m_grooveResults.clear();
ui.editEmptyGrooveCount->clear();
ui.editOccupiedGrooveCount->clear();
ui.editGrooveDetectTime->clear();
ui.tableGrooveResults->setRowCount(0);
ui.labelGrooveResultStatus->setText(QString::fromUtf8("识别结果:未执行"));
}
QRect YoloPanel::runYoloAndCrop(const QImage& img, int filterClass,
const QRect& hint, const QString& tag)
{
if (img.isNull() || !m_det->isLoaded()) return {};
int origW = img.width(), origH = img.height();
QImage img640 = img.scaled(640, 640, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
auto results = m_det->detect(img640, m_confThresh, m_nmsThresh, filterClass);
if (results.isEmpty()) {
emit logMessage(QString::fromUtf8("[%1] YOLO: 未检测到目标").arg(tag));
return {};
}
double sx = double(origW)/640.0, sy = double(origH)/640.0;
int bestIdx = 0;
if (hint.isValid()) {
QPointF hc(hint.center());
double bestDist = std::numeric_limits<double>::max();
for (int i = 0; i < results.size(); ++i) {
QPointF c(results[i].box.x()*sx + results[i].box.width()*sx/2.0,
results[i].box.y()*sy + results[i].box.height()*sy/2.0);
double d = QLineF(c, hc).length();
if (d < bestDist) { bestDist = d; bestIdx = i; }
}
} else {
float bc = 0;
for (int i = 0; i < results.size(); ++i)
if (results[i].conf > bc) { bc = results[i].conf; bestIdx = i; }
}
m_results = results;
QRectF b = results[bestIdx].box;
QRectF box(b.x()*sx, b.y()*sy, b.width()*sx, b.height()*sy);
double pw = box.width()*0.10, ph = box.height()*0.10;
box.adjust(-pw, -ph, pw, ph);
int x1 = qBound(0, int(box.x()), origW);
int y1 = qBound(0, int(box.y()), origH);
int w = qBound(10, int(box.width()), origW-x1);
int h = qBound(10, int(box.height()), origH-y1);
return QRect(x1, y1, w, h);
}