目标检测yolov8代码
时间: 2023-10-04 20:12:05 浏览: 113
YOLOv8目标检测源码.rar
5星 · 资源好评率100%
你可以在以下代码片段中找到使用YOLOv4进行目标检测的示例代码:
```python
import cv2
import numpy as np
# 加载YOLOv4模型
net = cv2.dnn.readNet("yolov4.weights", "yolov4.cfg")
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# 加载类别标签
classes = []
with open("coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
# 加载图像
image = cv2.imread("image.jpg")
height, width, channels = image.shape
# 对图像进行预处理
blob = cv2.dnn.blobFromImage(image, 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_SIMPLEX
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(image, (x, y), (x+w, y+h), color, 2)
cv2.putText(image, f"{label} {confidence:.2f}", (x, y-10), font, 0.5, color, 2)
# 显示结果图像
cv2.imshow("YOLOv4 Object Detection", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请确保你已经下载了YOLOv4的预训练权重文件(yolov4.weights)和配置文件(yolov4.cfg),以及类别标签文件(coco.names)。将这些文件与上述代码保存在同一个目录下,然后将图像文件命名为image.jpg,并将其放在同一个目录中。运行代码后,你将看到目标检测结果显示在窗口中。
请注意,这只是一个简单的示例代码,你可以根据自己的需求进行更改和扩展。另外,确保已经安装了OpenCV库,并且你可能需要根据自己的环境进行相应的配置和安装。
阅读全文