python绘制yolo标签

这么多篇csdn没有一篇令人满意的,真是垃圾桶吧这里

import numpy as np
import cv2
import matplotlib.pyplot as plt

# 坐标转换,原始存储的是YOLOv5格式
# Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right

def draw_yolo_labels(label_path, img_path,labels:list, is_show=True):
    # 读取图像
    img = cv2.imread(img_path)
    h1, w1 = img.shape[:2]

    
    # 读取 labels
    with open(label_path, 'r', encoding='utf-8') as f:
        boxes = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32)
    
    colors = {'chenpidan': (0, 0, 255), 'ckool': (0, 255, 0), 'meiyitian': (255, 0, 0)}
    
    for box in boxes:
        label_idx, x, y, w, h = box
        label = labels[int(label_idx)]
        color = colors[label]

        # 反归一化
        x_t = int(x * w1)
        y_t = int(y * h1)
        w_t = int(w * w1)
        h_t = int(h * h1)

        # 计算坐标
        top_left_x = int(x_t - w_t / 2)
        top_left_y = int(y_t - h_t / 2)
        bottom_right_x = int(x_t + w_t / 2)
        bottom_right_y = int(y_t + h_t / 2)

        # 绘制矩形框
        cv2.rectangle(img, (top_left_x, top_left_y), (bottom_right_x, bottom_right_y), color, 2)

        # 添加标签
        cv2.putText(img, label, (top_left_x, top_left_y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, color, 2)

    if is_show:
        # 使用 matplotlib 在 Jupyter 中显示图像
        plt.figure(figsize=(10, 10))
        plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))  # 转换为 RGB 格式以正确显示颜色
        plt.axis('off')  # 关闭坐标轴
        plt.show()

    return img

使用例


label_path = r'label.txt'
image_path = r'label.jpg'
labels = ['class1', 'c2', 'c3']

a=draw_yolo_labels(label_path, image_path)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值