yolov8预测图片
时间: 2023-10-23 13:15:04 浏览: 204
yolov8预测路标的代码、权重、示例图片和对应的推理结果
你可以使用以下代码来使用YOLOv4进行图片预测:
```python
import cv2
import numpy as np
# 加载模型和配置文件
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_PLAIN
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 = (0, 255, 0)
cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
cv2.putText(image, label + " " + str(round(confidence, 2)), (x, y + 30), font, 3, color, 3)
# 显示结果
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
请确保已经下载了YOLOv4的权重文件(yolov4.weights)、配置文件(yolov4.cfg)和类标签文件(coco.names),并将其放在与代码文件相同的目录下。同时将要预测的图片(image.jpg)也放在相同的目录下。运行代码后,你将会看到带有边框和标签的预测结果图像显示出来。
注意:YOLOv4是YOLOv3的改进版本,因此你也可以将代码中的模型文件和配置文件替换为YOLOv3的对应文件,以进行YOLOv3的图片预测。
阅读全文