废话不多说,直接上代码
#include <opencv2/opencv.hpp>
#include <opencv2/dnn/dnn.hpp>
#include <iostream>
int main() {
// 路径
std::string modelPath = "D:/yolo/datasets/CS/v5-7.0/yolov5s_best.onnx";
std::string imagePath = "D:/yolo/datasets/CS/images/20240619202642.jpg";
// 加载模型
cv::dnn::Net net = cv::dnn::readNet(modelPath);
// 检查模型是否成功加载
if (net.empty()) {
std::cerr << "Failed to load the model from: " << modelPath << std::endl;
return 1;
}
else {
std::cout << "Model loaded successfully from: " << modelPath << std::endl;
}
// 读取图像
cv::Mat frame = cv::imread(imagePath);
if (frame.empty()) {
std::cerr << "Could not read the image from: " << imagePath << std::endl;
return 1;
}
else {
std::cout << "Image loaded successfully from: " << imagePath << std::endl;
}
// 创建blob
cv::Mat blob;
cv::dnn::blobFromImage(frame, blob, 1 / 255.0, cv::Size(640, 640), cv::Scalar(0, 0, 0), true, false);
std::cout << "Blob created from image." << std::endl;
// 设置输入
net.setInput(blob);
// 前向传播
std::vector<cv::Mat> outputs;
net.forward(outputs, net.getUnconnectedOutLayersNames());
std::cout << "Forward pass completed." << std::endl;
// 处理检测
for (auto& output : outputs) {
std::cout << "Output rows: " << output.rows << ", columns: " << output.cols << std::endl;
for (int i = 0; i < output.rows; i++) {
const float* data = output.ptr<float>(i);
float x_center = data[0] * frame.cols;
float y_center = data[1] * frame.rows;
float width = data[2] * frame.cols;
float height = data[3] * frame.rows;
float confidence = data[4];
std::cout << "Detection " << i << ": " << "x_center: " << x_center << ", y_center: " << y_center;
std::cout << ", width: " << width << ", height: " << height << ", confidence: " << confidence << std::endl;
if (confidence > 0.75) {
cv::Mat scores = cv::Mat(1, 80, CV_32F, (void*)(data + 5)); // 根据您的类别数量调整
cv::Point classIdPoint;
double classConfidence;
cv::minMaxLoc(scores, 0, &classConfidence, 0, &classIdPoint);
if (classConfidence > 0.45) {
std::cout << "Class ID: " << classIdPoint.x << ", Confidence: " << classConfidence << std::endl;
}
}
}
}
// 显示结果
cv::imshow("YOLOv5 Detection", frame);
cv::waitKey(0);
return 0;
}