import torch
from yolov8.models.experimental import attempt_load
from yolov8.utils.datasets import LoadImages
from yolov8.utils.general import non_max_suppression, scale_coords
from yolov8.utils.torch_utils import select_device, time_synchronized
# 加载模型
device = select_device('') # 选择设备
model = attempt_load('yolov8/weights.pt', map_location=device) # 加载权重
# 加载数据
path = 'data/images' # 图像文件夹路径
imgsz = 640 # 输入图片大小
dataset = LoadImages(path, img_size=imgsz)
# 检测
for path, img, im0s, _ in dataset:
img = torch.from_numpy(img).to(device)
img = img.float() # uint8 to fp16/32
img /= 255.0 # 0 - 255 to 0.0 - 1.0
if img.ndimension() == 3:
img = img.unsqueeze(0)
# 推理和计时
pred = model(img, augment=False)[0]
# 应用NMS
pred = non_max_suppression(pred, 0.4, 0.5, classes=None, agnostic=False)
# Process detections
for i, det in enumerate(pred): # 检测到的每个图片
p, s, im0 = path, '', im0s
s += '%gx%g ' % img.shape[2:] # 打印图片信息
if len(det):
# 将坐标调整回原图片尺寸
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
# 打印结果
for c in det[:, -1].unique():
n = (det[:, -1] == c).sum() # 检测到的每类的数量
s += f'{n} {model.names[int(c)]}s, ' # 添加到字符串
# 写入结果
for *xyxy, conf, cls in reversed(det):
label = f'{model.names[int(cls)]} {conf:.2f}'
# 这里可以添加代码来绘制边界框等
# 打印进度
print(f'{p}: {s}')