yolov8检测保存图片 python
时间: 2024-03-27 16:34:07 浏览: 147
YOLOV8行人检测+数据集+pyqt界面
YOLOv3是一种基于深度学习的目标检测算法,它可以在图像中同时检测多个目标,并给出它们的位置和类别。YOv3的网络结构相对较简单但在速度和准确性方面表现出色。
如果你想使用YOv3进行目标检测并保存检测结果的图片,可以使用Python编程语言和相应的库来实现。以下是一个简单的示例代码:
```python
import cv2
import numpy as np
# 加载YOLOv3模型
net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
# 加载类别标签
classes = []
with open("coco.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
# 加载图像
image = cv2.imread("image.jpg")
# 获取图像尺寸
height, width, _ = image.shape
# 构建输入图像的blob
blob = cv2.dnn.blobFromImage(image, 1/255.0, (416, 416), swapRB=True, crop=False)
# 设置网络的输入
net.setInput(blob)
# 前向传播获取输出层
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
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)
class_ids.append(class_id)
confidences.append(float(confidence))
boxes.append([x, y, w, h])
# 应用非最大值抑制获取最终的检测结果
indices = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)
for i in indices:
i = i[0]
x, y, w, h = boxes[i]
label = 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), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
# 保存检测结果的图片
cv2.imwrite("result.jpg", image)
```
上述代码中,首先加载YOLOv3模型和类别标签。然后,读取待检测的图像,并将其转换为网络所需的输入格式。接下来,通过前向传播获取输出层的结果,并解析得到目标的位置、类别和置信度。最后,应用非最大值抑制算法获取最终的检测结果,并将结果绘制在图像上,最终保存为一张新的图片。
阅读全文