widerperson数据集转化为YOLO格式

  1. 先按照train.txt和val.txt中的内容,将训练集图片和注释全部放在train文件夹下,验证集也是一样。
import os
from pathlib import Path
from PIL import Image
import csv
import shutil


# coding=utf-8
def check_charset(file_path):
    import chardet
    with open(file_path, "rb") as f:
        data = f.read(4)
        charset = chardet.detect(data)['encoding']
    return charset


def convert(size, box0, box1, box2, box3):
    dw = 1. / size[0]
    dh = 1. / size[1]
    x = (box0 + box2) / 2 * dw
    y = (box1 + box3) / 2 * dh
    w = (box2 - box0) * dw
    h = (box3 - box1) * dh
    return (x, y, w, h)


if __name__ == '__main__':
    path = 'F:\dataset\WiderPerson/train.txt'
    with open(path, 'r') as f:
        img_ids = [x for x in f.read().splitlines()]

    for img_id in img_ids:  # '000040'
        img_path = 'F:\dataset\WiderPerson\Images/' + img_id + '.jpg'

        with Image.open(img_path) as Img:
            img_size = Img.size

        ans = ''

        label_path = img_path.replace('Images', 'Annotations') + '.txt'
        outpath = 'train/' + img_id + '.txt'

        with open(label_path, encoding=check_charset(label_path)) as file:
            line = file.readline()
            count = int(line.split('\n')[0])  # 里面行人个数
            line = file.readline()
            while line:
                cls = int(line.split(' ')[0])
                if cls == 1 or cls == 2 or cls == 3:
                    xmin = float(line.split(' ')[1])
                    ymin = float(line.split(' ')[2])
                    xmax = float(line.split(' ')[3])
                    ymax = float(line.split(' ')[4].split('\n')[0])
                    print(img_size[0], img_size[1], xmin, ymin, xmax, ymax)
                    bb = convert(img_size, xmin, ymin, xmax, ymax)
                    ans = ans + '1' + ' ' + ' '.join(str(a) for a in bb) + '\n'
                line = file.readline()
        with open(outpath, 'w') as outfile:
            outfile.write(ans)
        shutil.copy(img_path, 'train/' + img_id + '.jpg')

  1. 将图片和注释分开,放在各自的文件夹中
import shutil
import os
if __name__ == '__main__':
    label_path=r"train/"
    imgids = os.listdir(label_path)
    print(len(imgids))
    n=0
    for i in imgids:
        n += 1
        img_ids_path = label_path.replace('labels', 'images')+ i[0:6] +'.txt'
        To_imgpath=r'train\anno/'
        print(img_ids_path,To_imgpath,n)
        shutil.copy(img_ids_path, To_imgpath)


OK!!!

参考博客:https://blog.csdn.net/qq_44224801/article/details/123480032
参考博客:https://blog.csdn.net/wukong168/article/details/122697243

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值