记录C++调用yolo v5s模型onnx,利用opencv库

废话不多说,直接上代码

#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;
}

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值