Files
VisionGuide/source/YoloDetector.h
T

85 lines
3.0 KiB
C++
Raw Normal View History

2026-10-26 10:56:56 +08:00
//YoloDetector.h
#pragma once
#include <QObject>
#include <QImage>
#include <QString>
#include <QStringList>
#include <QVector>
#include <QRectF>
#include <memory>
#include <vector>
// ── Detection result ─────────────────────────────────────────────────────────
struct YoloResult {
QRectF box; // pixel coords in the original image
int classId = 0;
float conf = 0.f;
QString label;
};
// ── YoloDetector ─────────────────────────────────────────────────────────────
// All ONNXRuntime types are hidden in the .cpp via pimpl so this header
// can be included without pulling in onnxruntime headers everywhere.
class YoloDetector : public QObject
{
Q_OBJECT
public:
explicit YoloDetector(QObject* parent = nullptr);
~YoloDetector();
// Load an ONNX model exported from YOLOv8 (Ultralytics default format).
// Returns true on success. On failure, errorOccurred() is emitted.
bool loadModel(const QString& onnxPath);
bool isLoaded() const { return m_loaded; }
QString modelPath() const { return m_modelPath; }
int numClasses() const { return m_numClasses; }
int inputWidth() const { return m_inputW; }
int inputHeight() const { return m_inputH; }
// Override class names (e.g. {"镀金零件", "非镀金零件"}).
// If not called the detector uses "class0", "class1", …
void setClassNames(const QStringList& names);
QStringList classNames() const { return m_classNames; }
// Run detection and return raw results.
// filterClass: -1 = return all classes; >= 0 = only that class id.
QVector<YoloResult> detect(const QImage& img,
float confThresh = 0.25f,
float nmsThresh = 0.45f,
int filterClass = -1);
// Convenience: run detect() and return the image with boxes drawn.
QImage detectAndDraw(const QImage& img,
float confThresh = 0.25f,
float nmsThresh = 0.45f,
int filterClass = -1);
signals:
void modelLoaded(const QString& path);
void errorOccurred(const QString& msg);
private:
// pimpl – keeps ORT types out of the header
struct OrtImpl;
std::unique_ptr<OrtImpl> m_ort;
// Preprocess image to ORT input tensor format (RGB, 0-1 norm, resized to 640x640)
std::vector<float> preprocess(const QImage& img, int targetW, int targetH);
// Postprocess ORT output to YoloResult (includes NMS)
QVector<YoloResult> postprocess(const float* data, int numAnchors, int numFields,
int origW, int origH, float confThresh,
float nmsThresh, int filterClass);
// Non-Maximum Suppression (NMS)
QVector<YoloResult> nms(QVector<YoloResult>& candidates, float iouThresh);
// Private state
bool m_loaded = false;
QString m_modelPath;
int m_numClasses = 0;
int m_inputW = 640; // YOLOv8 default input width
int m_inputH = 640; // YOLOv8 default input height
QStringList m_classNames;
};