将yolo格式的label在对应图片上进行绘制

文章提供了一个Python脚本,用于读取YOLO格式的标签数据,并将其转化为图像的boundingbox坐标,通过绘制bbox来验证数据转化的正确性。脚本检查了可能影响训练效果的问题,特别是从YOLO格式到YOLOXxyxy格式的转换。如果转化有误,脚本可以帮助识别并修正问题。
摘要由CSDN通过智能技术生成

我通过格式转化得到了一组yolo格式的标签,在训练的过程中训练效果奇差无比,后来经过排查可能是yolo格式的数据转化过程中出了问题,因此我决定写个python进行验证。

注意一下这里是把yolo格式中xywh(x_center, y_center, bbox_width, bbox_height)的数据进行绘制,如果是yolox推理出的结果应该是xyxy格式的(x_min, y_min, x_max, y_max)的数据在下面for data in yolo_data的循环中直接输出就行。

import os
import cv2

def read_yolo_data(txt_path):
    yolo_data = []
    with open(txt_path, 'r') as file:
        for line in file:
            values = line.strip().split()
            class_id = int(values[0])
            x_center, y_center, bbox_width, bbox_height = map(float, values[1:])
            yolo_data.append((class_id, x_center, y_center, bbox_width, bbox_height))
    return yolo_data

def draw_bbox(image_path, yolo_data):
    img = cv2.imread(image_path)
    height, width, _ = img.shape

    for data in yolo_data:
        #如果是yolox的xyxy格式不用再进行转化了
        class_id, x_center, y_center, bbox_width, bbox_height = data
        x_min = int((x_center - bbox_width / 2) * width)
        y_min = int((y_center - bbox_height / 2) * height)
        x_max = int((x_center + bbox_width / 2) * width)
        y_max = int((y_center + bbox_height / 2) * height)

        cv2.rectangle(img, (x_min, y_min), (x_max, y_max), (0, 255, 0), 2)

    return img

def main():
    img_folder = 'C:/Users/yuqi zhang/Desktop/yolox_cow/train/images'
    txt_folder = 'C:/Users/yuqi zhang/Desktop/data'

    for file in os.listdir(txt_folder):
        if file.endswith('.txt'):
            txt_path = os.path.join(txt_folder, file)
            yolo_data = read_yolo_data(txt_path)

            image_path = os.path.join(img_folder, file[:-4] + '.jpg')
            img_with_bbox = draw_bbox(image_path, yolo_data)

            # If you want to display the image with bbox
            # cv2.imshow(f'Image with BBox: {file[:-4]}.jpg', img_with_bbox)
            # cv2.waitKey(0)
            # cv2.destroyAllWindows()

            # If you want to save the image with bbox
            output_path = os.path.join(img_folder, 'output', file[:-4] + '_with_bbox.jpg')
            os.makedirs(os.path.dirname(output_path), exist_ok=True)
            cv2.imwrite(output_path, img_with_bbox)
            print("finish:"+output_path)

if __name__ == '__main__':
    main()

只需要修改main中的两个路径就能运行了

输出路径在img_folder中的新建文件夹output中

经过验证确实是转化的时候出现问题了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值