YoloV8如何将标签绘制在原图中

为了对比训练结果和标签是否一致,有时候需要可视化标签图像进行对比查看,可通过如下代码查看自己标签在图像中的具体框

import os
import cv2
import numpy as np

# 输入和输出路径
images_path = 'images/val'  # 图像文件夹路径
labels_path = 'labels/val'  # 标签文件夹路径
output_path = 'output'      # 输出文件夹路径

# 确保输出文件夹存在
os.makedirs(output_path, exist_ok=True)

# 获取所有图像文件
image_files = [f for f in os.listdir(images_path) if f.endswith(('.bmp', '.jpg', '.jpeg', '.png'))]

for image_file in image_files:
    # 读取图像
    image_path = os.path.join(images_path, image_file)
    image = cv2.imread(image_path)
    height, width, _ = image.shape

    # 标签文件路径(假设标签文件名与图像文件名相同但扩展名为.txt)
    label_file = os.path.splitext(image_file)[0] + '.txt'
    label_path = os.path.join(labels_path, label_file)

    # 如果标签文件存在,读取标签
    if os.path.exists(label_path):
        with open(label_path, 'r') as f:
            lines = f.readlines()
            for line in lines:
                # 解析标签:类别 左上x 左上y 右上x 右上y 右下x 右下y 左下x 左下y
                parts = line.strip().split()
                class_id = int(parts[0])
                points = list(map(float, parts[1:]))

                # 归一化坐标转换为图像坐标
                points = [(int(p[0] * width), int(p[1] * height)) for p in zip(points[::2], points[1::2])]

                # 绘制多边形
                points = [(points[0][0], points[0][1]), (points[1][0], points[1][1]), 
                          (points[2][0], points[2][1]), (points[3][0], points[3][1])]
                cv2.polylines(image, [np.array(points, np.int32)], isClosed=True, color=(0, 255, 0), thickness=2)

    # 保存标注后的图像
    output_image_path = os.path.join(output_path, image_file)
    cv2.imwrite(output_image_path, image)

补充,部分人使用的格式为xywh,进行如下判断执行

# 添加到for line in lines:parts = line.strip().split()后即可
if len(parts) == 5:
   # 新格式:类别 中心点x 中心点y 宽w 高h
   class_id = int(parts[0])
   center_x = float(parts[1]) * width
   center_y = float(parts[2]) * height
   bbox_w = float(parts[3]) * width
   bbox_h = float(parts[4]) * height

   # 计算左上角和右下角坐标
   top_left = (int(center_x - bbox_w / 2), int(center_y - bbox_h / 2))
   bottom_right = (int(center_x + bbox_w / 2), int(center_y + bbox_h / 2))

   # 绘制矩形框
   cv2.rectangle(image, top_left, bottom_right, color=(255, 0, 0), thickness=2)
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值