21xrx.com
2024-09-20 00:34:58 Friday
登录
文章检索 我的文章 写文章
如何使用OpenCV调用YOLOv5
2023-09-15 21:53:47 深夜i     --     --
OpenCV YOLOv5 调用 使用 目标检测

OpenCV是一个开源的计算机视觉库,它提供了很多图像处理和计算机视觉方面的功能。而YOLOv5是一个非常流行的目标检测模型,它可以实现快速而准确的目标检测。本文将介绍如何使用OpenCV调用YOLOv5来进行目标检测。

首先,我们需要安装OpenCV和YOLOv5库。可以使用pip命令来安装它们:


pip install opencv-python

pip install yolov5

安装完成之后,我们需要下载YOLOv5的预训练模型。在YOLOv5的官方GitHub仓库中有多个预训练模型可供选择,可以根据具体需求选择一个合适的模型进行下载。下载完成后,将模型文件放在一个合适的位置。

接下来,我们可以开始编写使用OpenCV调用YOLOv5的代码。下面是一个简单的示例:

python

import cv2

from PIL import Image

import numpy as np

# 加载YOLOv5模型

net = cv2.dnn.readNet("path/to/model.pt", "path/to/model.yaml")

layer_names = net.getLayerNames()

output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]

# 加载图片并进行目标检测

img = cv2.imread("path/to/image.jpg")

height, width, channels = img.shape

blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False)

net.setInput(blob)

outs = net.forward(output_layers)

# 解析检测结果

class_ids = []

confidences = []

boxes = []

for out in outs:

  for detection in out:

    scores = detection[5:]

    class_id = np.argmax(scores)

    confidence = scores[class_id]

    if confidence > 0.5:

      center_x = int(detection[0] * width)

      center_y = int(detection[1] * height)

      w = int(detection[2] * width)

      h = int(detection[3] * height)

      x = int(center_x - w / 2)

      y = int(center_y - h / 2)

      class_ids.append(class_id)

      confidences.append(float(confidence))

      boxes.append([x, y, w, h])

# 对检测结果进行后处理

indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)

font = cv2.FONT_HERSHEY_SIMPLEX

for i in range(len(boxes)):

  if i in indexes:

    x, y, w, h = boxes[i]

    label = str(class_ids[i])

    confidence = confidences[i]

    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)

    cv2.putText(img, label, (x, y + 30), font, 1, (0, 255, 0), 2)

# 显示结果

cv2.imshow("Image", img)

cv2.waitKey(0)

cv2.destroyAllWindows()

在这个示例中,首先我们使用`cv2.dnn.readNet()`函数加载YOLOv5的模型文件和配置文件,并获取输出层的名称。然后,我们加载要进行目标检测的图片,并进行一些预处理。接下来,我们利用加载的模型进行目标检测,得到检测结果。最后,我们对检测结果进行解析和后处理,然后在图片上绘制目标框和类别标签,最终显示结果。

以上就是使用OpenCV调用YOLOv5进行目标检测的基本流程。你可以根据需要进行适当的调整和扩展,以满足具体的应用需求。通过将OpenCV和YOLOv5组合起来使用,你可以更加方便地实现目标检测任务。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复