from ultralytics import YOLO
model = YOLO('yolov8n.pt')
results = model.train(
data='D:/plate_dataset/plate.yaml',
epochs=50,
batch=8,
imgsz=640,
lr0=0.01,
classes=[0],
save=True,
device=0,
patience=10
)
#include <opencv2/opencv.hpp>
#include <opencv2/dnn.hpp>
#include <iostream>
#include <vector>
#include <string>
using namespace cv;
using namespace cv::dnn;
using namespace std;
const float CONF_THRESH = 0.5f;
const float NMS_THRESH = 0.4f;
const int INPUT_W = 640;
const int INPUT_H = 640;
const string MODEL_PATH = "D:/best.onnx";
const string CLASS_PATH = "D:/class_names.txt";
vector<string> readClassNames(const string& path) {
vector<string> classes;
ifstream file(path);
string line;
while (getline(file, line)) {
classes.push_back(line);
}
return classes;
}
void yoloDetect(Mat& img, Net& net, vector<string>& classes) {
int img_w = img.cols;
int img_h = img.rows;
Mat blob;
blobFromImage(img, blob, 1.0 / 255.0, Size(INPUT_W, INPUT_H), Scalar(0, 0, 0), true, false);
net.setInput(blob);
Mat outputs = net.forward("output0");
vector<int> class_ids;
vector<float> confs;
vector<Rect> boxes;
float* data = (float*)outputs.data;
int num_boxes = outputs.size[1];
for (int i = 0; i < num_boxes; i++) {
float conf = data[4];
if (conf < CONF_THRESH) continue;
float max_class_conf = 0;
int class_id = 0;
for (int j = 5; j < 6; j++) {
float class_conf = data[j];
if (class_conf > max_class_conf) {
max_class_conf = class_conf;
class_id = j - 5;
}
}
float cx = data[0] * img_w;
float cy = data[1] * img_h;
float w = data[2] * img_w;
float h = data[3] * img_h;
int x1 = max(0, int(cx - w / 2));
int y1 = max(0, int(cy - h / 2));
int x2 = min(img_w - 1, int(cx + w / 2));
int y2 = min(img_h - 1, int(cy + h / 2));
class_ids.push_back(class_id);
confs.push_back(conf * max_class_conf);
boxes.push_back(Rect(x1, y1, x2 - x1, y2 - y1));
data += 6;
}
vector<int> indices;
NMSBoxes(boxes, confs, CONF_THRESH, NMS_THRESH, indices);
Scalar color(0, 255, 0);
for (int idx : indices) {
Rect box = boxes[idx];
int class_id = class_ids[idx];
float conf = confs[idx];
rectangle(img, box, color, 2, 8);
string label = classes[class_id] + ":" + format("%.2f", conf);
int label_h = 25;
Rect label_rect(box.x, box.y - label_h, box.width, label_h);
rectangle(img, label_rect, color, -1);
putText(img, label, Point(box.x + 5, box.y - 5), FONT_HERSHEY_SIMPLEX, 0.6, Scalar(255, 255, 255), 1);
}
}
int main() {
Net net = readNetFromONNX(MODEL_PATH);
vector<string> classes = readClassNames(CLASS_PATH);
if (net.empty() || classes.empty()) {
cout << "模型或类别名加载失败!" << endl;
return -1;
}
net.setPreferableBackend(DNN_BACKEND_CUDA);
net.setPreferableTarget(DNN_TARGET_CUDA);
Mat img = imread("D:/test_plate.jpg");
if (img.empty()) {
cout << "图片读取失败!" << endl;
return -1;
}
yoloDetect(img, net, classes);
imshow("Plate Detection", img);
waitKey(0);
return 0;
}