首页 > 其他分享 >标注框图还原脚本(yolo格式)

标注框图还原脚本(yolo格式)

时间:2024-12-14 11:27:10浏览次数:8  
标签:img cv2 yolo list 框图 label path folder 标注

       因为在检测网上下载的数据集,检查一下label对img的标记是否正确,因此构建一个脚本,读取txt文件中的yolo类型标注,还原生成的框图,检查数据集标注是否正确

        运行结果

        

        下图img是我原始的img图像,我全部是jpg的后缀,txt是我的label标注的txt文件,注意是opencv图像存储的路径不能出现中文

        

        脚本源码

        

import os
import numpy as np
import cv2

# 修改输入图片文件夹
img_folder = r"D:/iSOOD_10481_v1.0/img/img-6/final/img"
img_list = os.listdir(img_folder)
img_list.sort()
# 修改输入标签文件夹
label_folder = r"D:/iSOOD_10481_v1.0/img/img-6/final/txt"
label_list = os.listdir(label_folder)
label_list.sort()

# 输出图片文件夹位置
output_folder = r"D:/iSOOD_10481_v1.0/img/img-6/final/1"  # 修改为你想要的新路径
if not os.path.exists(output_folder):
    os.mkdir(output_folder)

# colormap = [(0, 255, 0), (132, 112, 255), (0, 191, 255)]  # 色盘,可根据类别添加新颜色
labels = [
    "Combined sewer",
    "Rainwater",
    "Industrial wastewater",
    "Agricultural drainage",
    "Livestock breeding",
    "Aquaculture",
    "Surface runoff",
    "Watewater treatment plant",
    "Domestic wastewater",
    "Other"
]
colormap = [
    (32, 144, 140), (203, 71, 119), (187, 55, 84), (182, 54, 121), (124, 123, 120),
    (47, 20, 54), (225, 216, 225), (0, 64, 128), (93, 160, 75), (254, 253, 152)
]

# 坐标转换
def xywh2xyxy(x, w1, h1, img):
    label, x, y, w, h = x
    # 边界框反归一化
    x_t = x * w1
    y_t = y * h1
    w_t = w * w1
    h_t = h * h1
    # 计算坐标
    top_left_x = x_t - w_t / 2
    top_left_y = y_t - h_t / 2
    bottom_right_x = x_t + w_t / 2
    bottom_right_y = y_t + h_t / 2
    # 绘制矩形框
    cv2.rectangle(img, (int(top_left_x), int(top_left_y)), (int(bottom_right_x), int(bottom_right_y)), colormap[int(label)], 2)
    new_array[int(label)] += 1
    return img

if __name__ == '__main__':
    for i in range(len(img_list)):
        new_array = [0] * 10
        image_path = img_folder + "/" + img_list[i]
        label_path = label_folder + "/" + label_list[i]

        # 调试信息
        print("尝试读取图像:", image_path)

        # 读取图像文件
        img = cv2.imread(str(image_path))
        if img is None:
            print(f"无法读取图像: {image_path}")
            continue
        h, w = img.shape[:2]
        # 读取 labels
        with open(label_path, 'r') as f:
            lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32)
        # 绘制每一个目标
        for x in lb:
            # 反归一化并得到左上和右下坐标,画出矩形框
            img = xywh2xyxy(x, w, h, img)
        """
        # 直接查看生成结果图
        cv2.imshow('show', img)
        cv2.waitKey(0)
        """
        cv2.imwrite(output_folder + '/' + '{}.png'.format(image_path.split('/')[-1][:-4]), img)
        cunt = 0
        for x,y in enumerate(new_array):
            print("label:{},num:{}".format(labels[x],y))
            cunt += y

        print("cunt:{}".format(cunt))


标签:img,cv2,yolo,list,框图,label,path,folder,标注
From: https://blog.csdn.net/qq_57049935/article/details/144468483

相关文章