WiderPerson行人检测数据集转yolo格式

widerPerson数据集属于密集人群标注类型数据集
内部图片看标记为网络收集,很多带有水印
数据集对行人检测,分为5个类别,分别为1正常行人,2骑车人,3遮挡部分的人体,4人形物体,5无法区分的密集人堆
数据集文件编码为utf-16格式的文本文件,第一行为标注的个数,这个比较另类,需要在转换中去除
其他标注行格式为 编号,标注左上角,标注右上角,标注宽度,标注高度,转换yolo格式文件比较方便。

网络上有很多资料都是直接转换成voc格式的xml文件,为了方便测试,这里直接提供直接转成yolo格式的文件,保存下面为py格式文件,在根目录建立一个train文件夹,直接运行,会将train内生成对应训练yolo格式(悟空学堂)

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 = '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 = '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 or cls == 4:
                    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,2,3,4都保留并转换成1类,人堆那个用不到就剪除了

另外还有一种使用中情况,就是一些图片文件不适合的,会删除,删除后,需要把对应的yolo格式txt重新对应,把不想要的图片文件删除,建立一个train1文件夹,运行下面代码py文件,清理完成

import os
from pathlib import Path
from PIL import Image
import csv
import shutil
       
wd = os.getcwd()

anns = os.listdir('train')
for ann in anns:
    if ann[-3:] != 'jpg':
        continue
    shutil.copy(wd + '/train/' + ann[:-3] + 'jpg',wd + '/train1/' + ann[:-3] + 'jpg')
    shutil.copy(wd + '/train/' + ann[:-3] + 'txt',wd + '/train1/' + ann[:-3] + 'txt')


你可能感兴趣的:(yolo,深度学习,目标检测,计算机视觉)