【无标题】

项目场景:

矩形框识别

问题描述

代码

import torch
import cv2
import numpy as np
from ultralytics import YOLO
from torchvision import transforms

# 加载YOLOv8模型
model = YOLO('yolov8n.pt')  # 请根据实际情况加载已训练的权重
model.info()

# 图像预处理函数
transform = transforms.Compose([
    transforms.ToPILImage(),
    transforms.Resize((416, 416)),
    transforms.ToTensor()
])

# 读取图像
image = cv2.imread("your_image.jpg")  # 请替换成你的图像路径
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
input_image = transform(image).unsqueeze(0)

# 目标检测
with torch.no_grad():
    detections = model(input_image)

# 解析目标检测结果
# 请根据YOLOv8的输出格式来解析检测结果

# 假设detections是一个列表,每个元素包含检测结果,包括类别、置信度、边界框坐标等

# 在检测到的目标上绘制特征描述
for detection in detections[0]:
    class_id, confidence, x, y, w, h = detection[0:6]

    x1 = int(x - w / 2)
    y1 = int(y - h / 2)
    x2 = int(x + w / 2)
    y2 = int(y + h / 2)

    # 提取目标区域
    target = image[y1:y2, x1:x2]

    # 在目标上绘制特征描述,这里只是示例,您可以使用其他方法
    target = cv2.rectangle(target, (0, 0), (w, h), (0, 255, 0), 2)

# 保存结果图像
cv2.imwrite("result.jpg", image)

# 显示结果图像(可选)
cv2.imshow("Result", image)
cv2.waitKey(0)
cv2.destroyAllWindows()


---


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值