yolov8测试脚本
时间: 2023-12-12 19:35:53 浏览: 134
训练相关的脚本和配置文件
以下是yolov8测试脚本的示例代码:
```python
import cv2
import numpy as np
import onnxruntime as ort
# 加载模型
sess = ort.InferenceSession('models/yolov8s.onnx')
# 加载类别名称
with open('yolov8_onnx/coco.names', 'r') as f:
class_names = [cname.strip() for cname in f.readlines()]
# 定义输入和输出节点名称
input_name = sess.get_inputs()[0].name
output_names = [sess.get_outputs()[i].name for i in range(len(sess.get_outputs()))]
# 定义预处理函数
def preprocess(img):
# 缩放图像
img = cv2.resize(img, (416, 416))
# 转换颜色空间
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# 归一化像素值
img = img.astype(np.float32) / 255.0
# 转换维度顺序
img = np.transpose(img, [2, 0, 1])
# 添加批次维度
img = np.expand_dims(img, axis=0)
return img
# 定义后处理函数
def postprocess(outputs, conf_thresh=0.5, nms_thresh=0.5):
# 解析输出
boxes, scores, classes = [], [], []
for output in outputs:
output = np.squeeze(output)
num_classes = output.shape[1] - 5
for i in range(output.shape[0]):
box = output[i, :4]
score = output[i, 4]
class_idx = np.argmax(output[i, 5:])
class_score = output[i,5 + class_idx]
if score * class_score > conf_thresh:
x1, y1, x2, y2 = box
boxes.append([x1, y1, x2, y2])
scores.append(score * class_score)
classes.append(class_idx)
# 非极大值抑制
keep = cv2.dnn.NMSBoxes(boxes, scores, conf_thresh, nms_thresh)
# 构建检测结果
results = []
if len(keep) > 0:
for idx in keep.flatten():
x1, y1, x2, y2 = boxes[idx]
score = scores[idx]
class_idx = classes[idx]
class_name = class_names[class_idx]
results.append({'box': [x1, y1, x2, y2], 'score': score, 'class': class_name})
return results
# 加载图像
img = cv2.imread('yolov8_onnx/dog.jpg')
# 预处理图像
img = preprocess(img)
# 运行模型
outputs = sess.run(output_names, {input_name: img})
# 后处理输出
results = postprocess(outputs)
# 显示结果
for result in results:
x1, y1, x2, y2 = result['box']
score = result['score']
class_name = result['class']
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(img, f'{class_name} {score:.2f}', (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
cv2.imshow('result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
该脚本可以加载yolov8的onnx模型,并对一张图片进行推理,输出检测结果。在预处理函数中,将图像缩放到416x416大小,并归一化像素值;在后处理函数中,解析模型输出,进行非极大值抑制,并构建检测结果。最后,将检测结果绘制在原图上并显示出来。
阅读全文