pyside6将yolov8目标检测结果写入文件
时间: 2023-10-12 13:12:55 浏览: 88
要将YOLOv8目标检测结果写入文件,需要进行以下步骤:
1. 导入必要的库和模块:
```python
import cv2
import numpy as np
import os
```
2. 加载YOLOv8模型和配置文件:
```python
net = cv2.dnn.readNet('yolov8.weights', 'yolov8.cfg')
classes = []
with open('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()]
```
3. 加载图片并进行目标检测:
```python
img = cv2.imread('test.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)
```
4. 解析检测结果并将结果写入文件:
```python
# 类别ID、置信度和边界框坐标
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)
# 写入文件
with open('result.txt', 'w') as f:
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]
f.write(f'{label} {confidence:.2f} {x} {y} {x+w} {y+h}\n')
```
以上代码将检测到的目标类别、置信度和边界框坐标写入result.txt文件中。每行的格式为:类别名称 置信度 左上角x坐标 左上角y坐标 右下角x坐标 右下角y坐标。
阅读全文