使用colab进行yolov5小demo练习

本文介绍了如何使用YOLOv5深度学习模型在Python中对上传的动物图片进行目标检测,包括模型加载、图像预处理、预测及非极大值抑制后的结果输出。
摘要由CSDN通过智能技术生成

输入一张动物的图片进行目标检测和分类

!pip install yolov5
import torch
from PIL import Image
from torchvision import transforms
from yolov5.models.experimental import attempt_load
from yolov5.utils.general import non_max_suppression

# 加载YOLOv5模型
device = torch.device('cpu')  # 或者使用torch.device('cuda')以使用GPU
model = attempt_load("yolov5s.pt", device=device)

# 设置模型为评估模式
model.eval()

# 加载图像
image_path = "images/example_image.jpg"
image = Image.open(image_path)

# 调整图像大小为模型期望的输入大小(416x416)
resize_transform = transforms.Resize((416, 416))
image_resized = resize_transform(image)

# 定义图像转换
transform = transforms.Compose([
    transforms.ToTensor(),
])

# 对图像进行转换
input_tensor = transform(image_resized).unsqueeze(0).to(device)

# 进行目标检测
with torch.no_grad():
    results = model(input_tensor)

# 对结果进行非极大值抑制
results = non_max_suppression(results, conf_thres=0.3)

# 如果检测到目标,打印检测到的目标信息
if results is not None and len(results[0]) > 0:
    for detection in results[0]:
        print(f"类别: {detection[-1]}, 置信度: {detection[4]}, 边界框: {detection[:4]}")
else:
    print("未检测到任何目标。")
返回结果:
Fusing layers... 
YOLOv5s summary: 270 layers, 7235389 parameters, 0 gradients, 16.6 GFLOPs
类别: 17.0, 置信度: 0.8820466995239258, 边界框: tensor([ 95.17632,  88.61916, 327.81903, 387.15582])

图片 baidu

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值