21xrx.com
2024-05-20 05:07:52 Monday
登录
文章检索 我的文章 写文章
使用OpenCV调用YOLO进行图像识别
2023-09-21 07:37:06 深夜i     --     --
OpenCV YOLO 图像识别 算法 计算机视觉

OpenCV是一个广泛使用的开源计算机视觉库,而YOLO(You Only Look Once)则是一种流行的实时目标检测算法。本文将介绍如何使用OpenCV调用YOLO进行图像识别。

首先,我们需要下载并配置YOLO的权重文件和配置文件。这些文件定义了YOLO所需的神经网络架构与参数。可以在YOLO的官方网站上找到相关的文件。

接下来,我们需要在Python中安装OpenCV和YOLO的相关依赖。可以使用pip命令来安装这些依赖项。

安装完所需的依赖项后,我们可以开始编写Python代码来调用OpenCV和YOLO进行图像识别。首先,我们需要导入所需的库:

python

import cv2

import numpy as np

接下来,我们需要加载YOLO的网络模型和权重文件:

python

net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")

然后,我们需要定义YOLO所需的类别标签:

python

classes = []

with open("coco.names", "r") as f:

  classes = [line.strip() for line in f.readlines()]

接下来,我们需要设置输入图像的大小和缩放因子:

python

height, width = frame.shape[:2]

scale = 0.00392

然后,我们需要将输入图像转换为YOLO所需的格式:

python

blob = cv2.dnn.blobFromImage(frame, scale, (416,416), (0,0,0), True, crop=False)

接下来,我们需要将转换后的图像输入到YOLO的网络模型中并获取预测结果:

python

net.setInput(blob)

outs = net.forward(net.getUnconnectedOutLayersNames())

最后,我们需要解析预测结果并绘制检测框:

python

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)

for i in range(len(boxes)):

  if i in indexes:

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

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

    confidence = confidences[i]

    color = (255, 0, 0)

    cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)

    cv2.putText(frame, label + " " + str(round(confidence, 2)), (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)

最后,我们可以显示并保存检测结果的图像:

python

cv2.imshow("YOLO Image Recognition", frame)

cv2.waitKey(0)

cv2.destroyAllWindows()

使用OpenCV调用YOLO进行图像识别可以使我们在实时场景中快速而准确地检测出目标物体。通过以上的步骤,我们可以轻松地实现这一目标。希望本文对您有帮助!

  
  

评论区

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