项目场景:
矩形框识别
问题描述
代码
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()
---