21xrx.com
2025-03-30 08:23:10 Sunday
文章检索 我的文章 写文章
C++使用OpenCV部署YOLOv5模型
2023-07-02 22:47:32 深夜i     22     0
C++ OpenCV YOLOv5 部署 模型

近年来,物体检测技术在计算机视觉领域得到了广泛的关注和研究。其中,YOLO系列模型就是一个非常出色的物体检测模型。在这篇文章中,我们将讨论如何在C++中使用OpenCV部署YOLOv5模型。

首先,我们需要下载YOLOv5模型的权重文件。这些权重文件可以从GitHub上的开源项目中下载。下载完毕后,我们需要下载OpenCV库。OpenCV是一个广泛使用的计算机视觉库,提供了许多有用的函数和算法。它可以帮助我们在C++中轻松加载和处理图像。

接下来,我们需要编写一些C++代码来加载模型并运行推理。以下是一个使用OpenCV和YOLOv5模型进行物体检测的示例代码:

#include <iostream>
#include "opencv2/opencv.hpp"
using namespace cv;
using namespace std;
int main(int argc, char **argv) {
  // Load the YOLOv5 model
  string modelConfiguration = "yolov5.cfg";
  string modelWeights = "yolov5.weights";
  dnn::Net net = dnn::readNetFromDarknet(modelConfiguration, modelWeights);
  // Load the input image
  Mat image = imread("test.jpg");
  // Create a 4D blob from the input image and set the input of the network to the blob
  Mat blob = dnn::blobFromImage(image, 1 / 255.0, Size(416, 416), Scalar(0, 0, 0), true, false);
  net.setInput(blob);
  // Run forward pass to get output of the output layers
  vector<Mat> outputs;
  net.forward(outputs, net.getUnconnectedOutLayersNames());
  // Process each output layer
  for (int i = 0; i < outputs.size(); i++) {
    Mat detectionMat = outputs[i];
    // Loop over all detections and draw bounding boxes around the objects
    for (int j = 0; j < detectionMat.rows; j++) {
      float score = detectionMat.at<float>(j, 5);
      if (score > 0.5) {
        float x = detectionMat.at<float>(j, 0) * image.cols;
        float y = detectionMat.at<float>(j, 1) * image.rows;
        float width = detectionMat.at<float>(j, 2) * image.cols;
        float height = detectionMat.at<float>(j, 3) * image.rows;
        float x1 = x - width / 2;
        float y1 = y - height / 2;
        rectangle(image, Point(x1, y1), Point(x1 + width, y1 + height), Scalar(0, 255, 0), 2);
      }
    }
  }
  // Show the image with the detected objects
  imshow("YOLOv5 object detection", image);
  waitKey(0);
}

上面的代码首先加载了YOLOv5模型的权重文件,然后加载测试图片。然后,它将图像转换为4D的blob,然后将其设置为网络的输入。接下来,网络运行推理并得到输出层的输出。最后,代码循环遍历每个检测,并在图像中绘制由该检测生成的边界框。

最后,当我们编译并运行这个程序时,我们将得到一个显示检测到的对象的图像。您可以调整代码以便更改模型和输入图像的参数,以实现不同的物体检测任务。

总之,使用OpenCV和YOLOv5模型在C++中进行物体检测是非常简单和有用的。我们只需要加载模型、加载图像、处理输出并绘制边界框。这使得利用YOLOv5模型进行计算机视觉任务变得更加简单和快速。

  
  

评论区

请求出错了