根据YOLO格式标注信息在原图像上框出目标

import cv2
import matplotlib.pyplot as plt

# 读取图像
image_path = r'D:\Downloads\dataset\coco\000000000036.jpg' # 图像路径
image = cv2.imread(image_path)
height, width, _ = image.shape

# 读取YOLO格式的标注文件
annotation_path = r'D:\Downloads\dataset\coco\000000000036.txt' # yolo标注txt文件路径
with open(annotation_path, 'r') as file:
    lines = file.readlines()

# 解析标注信息并绘制边界框
for line in lines:
    class_id, x_center, y_center, box_width, box_height = map(float, line.strip().split())

    # 转换为图像坐标
    x_center *= width
    y_center *= height
    box_width *= width
    box_height *= height

    # 计算左上角和右下角的坐标
    x1 = int(x_center - box_width / 2)
    y1 = int(y_center - box_height / 2)
    x2 = int(x_center + box_width / 2)
    y2 = int(y_center + box_height / 2)

    # 绘制矩形框
    cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
    # 你可以选择在框上标记类别ID
    cv2.putText(image, str(int(class_id)), (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)

# 使用matplotlib显示图像
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.title('Image with Bounding Boxes')
plt.axis('off')  # 不显示坐标轴
plt.show()

# 保存带框的图像
output_image_path = r'D:\Downloads\dataset\coco\output_image.jpg' # 保存带框图像的路径
cv2.imwrite(output_image_path, image)

原图像为:

带标注框的图像为:

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用OpenCV库来可视化YOLO格式的数据集并绘制边界。下面是一个简单的示例代码,可以帮助你完成这个任务: ```python import cv2 import numpy as np def visualize_dataset(image_path, label_path, class_names): image = cv2.imread(image_path) height, width, _ = image.shape with open(label_path, 'r') as f: lines = f.readlines() for line in lines: # 解析边界信息 class_id, x, y, w, h = map(float, line.split()) class_id = int(class_id) x = int((x - w/2) * width) y = int((y - h/2) * height) w = int(w * width) h = int(h * height) # 绘制边界 cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.putText(image, class_names[class_id], (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2) cv2.imshow('Image', image) cv2.waitKey(0) cv2.destroyAllWindows() # 设置类别名称和标签路径 class_names = ['person', 'car', 'cat'] # 替换成你的类别名称 label_path = 'path/to/labels.txt' # 替换成你的标签文件路径 image_path = 'path/to/image.jpg' # 替换成你的图像文件路径 # 可视化数据集 visualize_dataset(image_path, label_path, class_names) ``` 在这个示例中,你需要将类别名称、标签文件路径和图像文件路径替换成你自己的路径。确保标签文件格式YOLO格式一致,每行包含了一个边界的类别ID和边界的中心坐标、宽度和高度。 运行这段代码后,你会看到一个显示了边界图像窗口。边界使用绿色线条绘制在图像上,并显示了对应的类别名称。你可以使用键盘上的任意按键来关闭图像窗口。 希望这个示例能帮助到你!如果有任何疑问,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值