在 Python 中使用 YOLO(You Only Look Once)进行图像识别需要使用相应的库和模型。以下是一个使用 OpenCV 和 YOLO 模型进行图像目标检测的示例:
在这个示例中,需要更改路径 yolo_weights/yolov3.weights
, yolo_config/yolov3.cfg
, yolo_data/coco.names
为你所使用的 YOLO 模型的权重文件、配置文件和类别名称文件的路径。确保你已经下载了相应的权重、配置文件以及类别名称文件。
此代码通过加载预训练的 YOLO 模型进行图像目标检测,并在图像中绘制检测到的边界框和标签。
pip install opencv-python
import cv2
import numpy as np
# 加载 YOLO
net = cv2.dnn.readNet("yolo_weights/yolov3.weights", "yolo_config/yolov3.cfg")
classes = []
with open("yolo_data/coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
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)
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
# 去除多余的框
indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
# 绘制边界框和标签
font = cv2.FONT_HERSHEY_PLAIN
colors = np.random.uniform(0, 255, size=(len(classes), 3))
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = str(classes[class_ids[i]])
color = colors[class_ids[i]]
cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
cv2.putText(img, label, (x, y + 30), font, 3, color, 3)
# 显示结果
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()