21xrx.com
2024-05-20 10:01:43 Monday
登录
文章检索 我的文章 写文章
使用OpenCV YOLOv5进行目标检测和跟踪图片
2023-10-04 18:08:12 深夜i     --     --
OpenCV YOLOv5 目标检测 跟踪 图片

OpenCV YOLOv5是一种强大的工具,可以通过图像处理技术进行目标检测和跟踪。在本文中,我们将介绍如何使用OpenCV YOLOv5来实现这些功能。

首先,我们需要安装OpenCV和YOLOv5。可以通过在终端中运行相应的命令来安装它们。一旦安装完成,我们就可以开始了。

要进行图像目标检测,我们首先需要加载YOLOv5预训练的权重。这些权重文件可以从YOLOv5官方网站上下载。然后,我们可以使用OpenCV的dnn模块来加载权重。

import cv2

# 加载YOLOv5预训练权重

net = cv2.dnn.readNetFromDarknet("yolov5.weights", "yolov5.cfg")

接下来,我们可以读取一张图片,并将其传递给YOLOv5模型进行目标检测。

# 读取图片

image = cv2.imread("image.jpg")

# 创建一个blob

blob = cv2.dnn.blobFromImage(image, 1/255.0, (416, 416), swapRB=True, crop=False)

# 将blob传递给模型

net.setInput(blob)

# 获取网络输出层的名称

layer_names = net.getLayerNames()

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

# 前向传播

outputs = net.forward(output_layers)

现在,我们可以遍历YOLOv5的输出,并提取每个检测到的对象的位置和类别。

# 初始化一些参数

boxes = []

confidences = []

class_ids = []

width = image.shape[1]

height = image.shape[0]

# 遍历输出

for output in outputs:

  for detection in output:

    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)

      # 添加检测结果到相应的列表中

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

      confidences.append(float(confidence))

      class_ids.append(class_id)

接下来,我们可以使用非极大值抑制方法过滤掉重叠的检测结果。

# 使用非极大值抑制方法过滤掉重叠的检测结果

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

最后,我们可以在原始图片上绘制边界框和标签,以标识检测到的对象。

# 在原始图片上画出边界框和标签

for i in indices:

  i = i[0]

  box = boxes[i]

  x, y, w, h = box

  label = str(classes[class_ids[i]])

  confidence = confidences[i]

  # 绘制边框

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

  # 绘制标签

  cv2.putText(image, f"{label}: {confidence:.2f}", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

最后,我们可以将处理后的图片显示出来。

# 显示图片

cv2.imshow("Image", image)

cv2.waitKey(0)

cv2.destroyAllWindows()

通过以上步骤,我们使用OpenCV YOLOv5成功地进行了目标检测和跟踪图片。这个强大的工具在许多计算机视觉应用中都有广泛的应用,包括监控系统、自动驾驶和工业检测等。希望这篇文章对你有所帮助!

  
  

评论区

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