yolov8onnx推理代码
时间: 2025-02-15 16:35:13 浏览: 46
### YOLOv8 ONNX 推理代码示例
对于YOLOv8模型,在ONNX Runtime环境下进行推理可以按照如下Python代码实现:
```python
import onnxruntime as ort
import numpy as np
from PIL import Image, ImageDraw
import cv2
def preprocess(image_path):
image = Image.open(image_path).convert('RGB')
image_resized = image.resize((640, 640))
img_array = np.array(image_resized)
# Normalize to [0, 1] and HWC to CHW format then add batch dimension.
input_tensor = (img_array / 255.0)[np.newaxis, :, :, :].transpose(0, 3, 1, 2).astype(np.float32)
return input_tensor
def postprocess(outputs, conf_threshold=0.7, iou_threshold=0.5):
boxes, scores, class_ids = [], [], []
output = outputs[0][0]
for detection in output:
score = float(detection[4])
if score >= conf_threshold:
classes_scores = detection[5:]
class_id = np.argmax(classes_scores)
if classes_scores[class_id] > score:
box = [
int(detection[0] - detection[2]/2),
int(detection[1] - detection[3]/2),
int(detection[0] + detection[2]/2),
int(detection[1] + detection[3]/2)]
boxes.append(box)
scores.append(score)
class_ids.append(class_id)
indices = cv2.dnn.NMSBoxes(
bboxes=boxes,
scores=scores,
score_threshold=conf_threshold,
nms_threshold=iou_threshold
)
filtered_boxes, filtered_scores, filtered_class_ids = [], [], []
for index in indices:
filtered_boxes.append(boxes[index])
filtered_scores.append(scores[index])
filtered_class_ids.append(class_ids[index])
return filtered_boxes, filtered_scores, filtered_class_ids
if __name__ == "__main__":
session = ort.InferenceSession("yolov8.onnx", providers=['CUDAExecutionProvider'])
input_name = session.get_inputs()[0].name
test_image_path = "test.jpg"
input_data = preprocess(test_image_path)
raw_result = session.run(None, {input_name: input_data})
boxes, scores, class_ids = postprocess(raw_result)
draw = ImageDraw.Draw(Image.open(test_image_path))
for idx, bbox in enumerate(boxes):
label = f"{class_ids[idx]}:{scores[idx]:.2f}"
draw.rectangle(bbox, outline="red", width=3)
draw.text((bbox[0], bbox[1]), label, fill="white")
result_img = Image.open(test_image_path)
result_img.show()
```
上述代码展示了如何加载一个预训练好的YOLOv8 ONNX模型,并通过给定的一张图像执行目标检测任务。此过程涉及到了输入数据的前处理以及输出结果后的后处理操作[^1]。
阅读全文
相关推荐


















