基于YOLO (You only look once)、进行目标识别的算法代码
时间: 2024-04-10 09:28:04 浏览: 172
对于基于YOLO的目标识别算法,以下是一个简单的代码示例:
```python
import cv2
import numpy as np
# 加载YOLO模型
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
# 获取所有类别名称
with open("coco.names", "r") as f:
classes = f.read().splitlines()
# 加载图像并进行预处理
img = cv2.imread("image.jpg")
height, width, _ = img.shape
# 构建输入blob
blob = cv2.dnn.blobFromImage(img, 1/255.0, (416, 416), swapRB=True, crop=False)
# 设置输入blob到网络中
net.setInput(blob)
# 运行前向传播以获取输出层
output_layers_names = net.getUnconnectedOutLayersNames()
layer_outputs = net.forward(output_layers_names)
# 初始化列表来存储检测结果
boxes = []
confidences = []
class_ids = []
# 遍历每个输出层
for output in layer_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)
# 存储边界框、置信度和类别ID
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 = classes[class_ids[i]]
confidence = confidences[i]
color = colors[class_ids[i]]
cv2.rectangle(img, (x, y), (x + w, y + h), color, 2)
cv2.putText(img, f"{label} {confidence:.2f}", (x, y - 5), font, 1, color, 2)
# 显示结果图像
cv2.imshow("Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请确保已经下载了YOLO的权重文件(`yolov3.weights`)、配置文件(`yolov3.cfg`)和类别名称文件(`coco.names`)。你可以从YOLO官方网站下载这些文件。
这段代码加载了YOLO模型并使用它在图像上进行目标识别。它将检测到的目标用边界框和类别标签进行绘制,并显示结果图像。请注意,此代码示例仅适用于YOLOv3模型,如果你使用其他版本的YOLO模型,可能需要相应地进行修改。
阅读全文