yolov8预测绘图
时间: 2025-02-17 21:20:24 浏览: 55
### YOLOv8 预测结果绘图方法
为了实现YOLOv8预测结果的可视化,在`predictor.py`文件中包含了推理和预测逻辑,这部分代码负责加载模型并处理输入数据以获得预测结果[^1]。然而,具体的绘制功能通常不在该模块内完成。
对于绘制预测框的操作,一般会编写一个辅助函数来遍历检测到的对象列表,并利用诸如OpenCV这样的库来进行图形绘制。下面是一个简单的Python代码片段展示如何基于YOLOv8的输出结果创建带有边界框和标签的图像:
```python
import cv2
from pathlib import Path
def plot_results(image, detections, class_names, output_path=None):
"""
将YOLOv8的检测结果显示在给定图片上
参数:
image (numpy.ndarray): 输入图像数组.
detections (list of dict): 检测结果列表,每个字典应包含'bbox', 'confidence', 和'class'.
class_names (dict or list): 类别名称映射表.
output_path (str, optional): 如果提供,则保存带标注后的图像路径,默认不保存.
返回值:
numpy.ndarray: 已经画好边界的图像副本.
"""
img_copy = image.copy()
for det in detections:
bbox = det['bbox']
conf = det['confidence']
cls_id = int(det['class'])
label = f'{class_names[cls_id]} {conf:.2f}'
color = tuple(map(int, np.random.randint(0, 255, size=3)))
# Draw bounding box and put text on it
pt1 = (int(bbox[0]), int(bbox[1]))
pt2 = (int(bbox[2]), int(bbox[3]))
font_scale = max(img_copy.shape[:2]) / 600
cv2.rectangle(img_copy, pt1, pt2, color=color, thickness=2)
cv2.putText(
img_copy,
label,
org=(pt1[0], pt1[1]-10),
fontFace=cv2.FONT_HERSHEY_SIMPLEX,
fontScale=min(font_scale, 1),
color=color,
thickness=int(max(round(font_scale * 2), 1))
)
if output_path is not None:
path = Path(output_path).with_suffix('.jpg')
cv2.imwrite(str(path), img_copy)
return img_copy
```
此函数接收原始图像、由YOLOv8产生的检测对象以及类别名映射作为参数,并返回一张已经标记了所有识别物体的新图像。如果指定了`output_path`,则还会将这张新图像保存至指定位置。
阅读全文
相关推荐


















