widerface数据集下载及转voc2007格式(基于python2.7和python3.5)

最近看了看YOLO从v1到v3,想用widerface数据集训练yolov3去进行人脸检测。
首先需要做的就是将widerface数据集的格式转化为VOC格式。
由于编程能力不强,在网上看了看代码,发现 https://www.cnblogs.com/linyuanzhou/p/6043436.html
为了省事,便借用一下,但是由于他的代码估计是基于python2.7,实测python2.7可以在直接运行他的代码。
在我用python3.5运行时,会有版本不兼容的状况。为此我对代码进行了一些小的修改,放在这里让大家更加方便吧。

下图为目录结构:

                                                                          

#基于python2.7的代码(我不是原作者)

 

# -*- coding: utf-8 -*-
"""
Created on 17-5-27
@author: zly 
"""
from skimage import io
import shutil
import random
import os
import string
 
headstr = """\
<annotation>
    <folder>VOC2007</folder>
    <filename>%06d.jpg</filename>
    <source>
        <database>My Database</database>
        <annotation>PASCAL VOC2007</annotation>
        <image>flickr</image>
        <flickrid>NULL</flickrid>
    </source>
    <owner>
        <flickrid>NULL</flickrid>
        <name>company</name>
    </owner>
    <size>
        <width>%d</width>
        <height>%d</height>
        <depth>%d</depth>
    </size>
    <segmented>0</segmented>
"""
objstr = """\
    <object>
        <name>%s</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>%d</xmin>
            <ymin>%d</ymin>
            <xmax>%d</xmax>
            <ymax>%d</ymax>
        </bndbox>
    </object>
"""
 
tailstr = '''\
</annotation>
'''
 
def all_path(filename):
    return os.path.join('widerface', filename)
 
def writexml(idx, head, bbxes, tail):
    filename = all_path("Annotations/%06d.xml" % (idx))
    f = open(filename, "w")
    f.write(head)
    for bbx in bbxes:
        f.write(objstr % ('face', bbx[0], bbx[1], bbx[0] + bbx[2], bbx[1] + bbx[3]))
    f.write(tail)
    f.close()
 
 
def clear_dir():
    if shutil.os.path.exists(all_path('Annotations')):
        shutil.rmtree(all_path('Annotations'))
    if shutil.os.path.exists(all_path('ImageSets')):
        shutil.rmtree(all_path('ImageSets'))
    if shutil.os.path.exists(all_path('JPEGImages')):
        shutil.rmtree(all_path('JPEGImages'))
 
    shutil.os.mkdir(all_path('Annotations'))
    shutil.os.makedirs(all_path('ImageSets/Main'))
    shutil.os.mkdir(all_path('JPEGImages'))
 
 
def excute_datasets(idx, datatype):
    f = open(all_path('ImageSets/Main/' + datatype + '.txt'), 'a')
    f_bbx = open(all_path('wider_face_split/wider_face_' + datatype + '_bbx_gt.txt'), 'r')
 
    while True:
        filename = string.strip(f_bbx.readline(), '\n')
        if not filename:
            break
        im = io.imread(all_path('WIDER_' + datatype + '/images/'+filename))
        head = headstr % (idx, im.shape[1], im.shape[0], im.shape[2])
        nums = string.strip(f_bbx.readline(), '\n')
        bbxes = []
        for ind in xrange(string.atoi(nums)):
            bbx_info = string.split(string.strip(f_bbx.readline(), ' \n'), ' ')
            bbx = [string.atoi(bbx_info[i]) for i in range(len(bbx_info))]
            #x1, y1, w, h, blur, expression, illumination, invalid, occlusion, pose
            if bbx[7]==0:
                bbxes.append(bbx)
        writexml(idx, head, bbxes, tailstr)
        shutil.copyfile(all_path('WIDER_' + datatype + '/images/'+filename), all_path('JPEGImages/%06d.jpg' % (idx)))
        f.write('%06d\n' % (idx))
        idx +=1
    f.close()
    f_bbx.close()
    return idx
 
 
# 打乱样本
def shuffle_file(filename):
    f = open(filename, 'r+')
    lines = f.readlines()
    random.shuffle(lines)
    f.seek(0)
    f.truncate()
    f.writelines(lines)
    f.close()
 
 
if __name__ == '__main__':
    clear_dir()
    idx = 1
    idx = excute_datasets(idx, 'train')
    idx = excute_datasets(idx, 'val')

下面是我修改后的基于python3.5

 

# -*- coding: utf-8 -*-
"""
Created on 18-5-13
@author: CHR
"""
from skimage import io
import shutil
import random
import os
import string
 
headstr = """\
<annotation>
    <folder>VOC2007</folder>
    <filename>%06d.jpg</filename>
    <source>
        <database>My Database</database>
        <annotation>PASCAL VOC2007</annotation>
        <image>flickr</image>
        <flickrid>NULL</flickrid>
    </source>
    <owner>
        <flickrid>NULL</flickrid>
        <name>company</name>
    </owner>
    <size>
        <width>%d</width>
        <height>%d</height>
        <depth>%d</depth>
    </size>
    <segmented>0</segmented>
"""
objstr = """\
    <object>
        <name>%s</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>%d</xmin>
            <ymin>%d</ymin>
            <xmax>%d</xmax>
            <ymax>%d</ymax>
        </bndbox>
    </object>
"""
 
tailstr = '''\
</annotation>
'''
 
def all_path(filename):
    return os.path.join('widerface', filename)
 
def writexml(idx, head, bbxes, tail):
    filename = all_path("Annotations/%06d.xml" % (idx))
    f = open(filename, "w")
    f.write(head)
    for bbx in bbxes:
        f.write(objstr % ('face', bbx[0], bbx[1], bbx[0] + bbx[2], bbx[1] + bbx[3]))
    f.write(tail)
    f.close()
 
 
def clear_dir():
    if shutil.os.path.exists(all_path('Annotations')):
        shutil.rmtree(all_path('Annotations'))
    if shutil.os.path.exists(all_path('ImageSets')):
        shutil.rmtree(all_path('ImageSets'))
    if shutil.os.path.exists(all_path('JPEGImages')):
        shutil.rmtree(all_path('JPEGImages'))
 
    shutil.os.mkdir(all_path('Annotations'))
    shutil.os.makedirs(all_path('ImageSets/Main'))
    shutil.os.mkdir(all_path('JPEGImages'))
 
 
def excute_datasets(idx, datatype):
    f = open(all_path('ImageSets/Main/' + datatype + '.txt'), 'a')
    f_bbx = open(all_path('wider_face_split/wider_face_' + datatype + '_bbx_gt.txt'), 'r')
 
    while True:
        filename = f_bbx.readline().strip('\n')
        if not filename:
            break
        im = io.imread(all_path('WIDER_' + datatype + '/images/'+filename))
        head = headstr % (idx, im.shape[1], im.shape[0], im.shape[2])
        nums = f_bbx.readline().strip('\n')
        bbxes = []
        for ind in range(int(nums)):
            bbx_info = f_bbx.readline().strip(' \n').split(' ')
            bbx = [int(bbx_info[i]) for i in range(len(bbx_info))]
            #x1, y1, w, h, blur, expression, illumination, invalid, occlusion, pose
            if bbx[7]==0:
                bbxes.append(bbx)
        writexml(idx, head, bbxes, tailstr)
        shutil.copyfile(all_path('WIDER_' + datatype + '/images/'+filename), all_path('JPEGImages/%06d.jpg' % (idx)))
        f.write('%06d\n' % (idx))
        idx +=1
    f.close()
    f_bbx.close()
    return idx
 
 
# 打乱样本
def shuffle_file(filename):
    f = open(filename, 'r+')
    lines = f.readlines()
    random.shuffle(lines)
    f.seek(0)
    f.truncate()
    f.writelines(lines)
    f.close()
 
 
if __name__ == '__main__':
    clear_dir()
    idx = 1
    idx = excute_datasets(idx, 'train')
    idx = excute_datasets(idx, 'val')

这里主要是记录我的学习过程,并分享,如有错误,望大家指出。 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个将COCO数据集格式换为VOC数据集格式Python代码示例: ```python import os import shutil import json import xml.etree.ElementTree as ET from PIL import Image # COCO数据集路径 coco_path = '/path/to/coco/dataset/' # VOC数据集路径 voc_path = '/path/to/voc/dataset/' # 创建VOC数据集所需的文件夹 if not os.path.exists(voc_path): os.makedirs(voc_path) if not os.path.exists(os.path.join(voc_path, 'Annotations')): os.makedirs(os.path.join(voc_path, 'Annotations')) if not os.path.exists(os.path.join(voc_path, 'JPEGImages')): os.makedirs(os.path.join(voc_path, 'JPEGImages')) if not os.path.exists(os.path.join(voc_path, 'ImageSets')): os.makedirs(os.path.join(voc_path, 'ImageSets', 'Main')) # 读取COCO数据集标注文件 with open(os.path.join(coco_path, 'annotations.json'), 'r') as f: annotations = json.load(f) # 处理每个图像 for image in annotations['images']: # 读取图像 image_file = os.path.join(coco_path, 'images', image['file_name']) im = Image.open(image_file) # 保存图像 im.save(os.path.join(voc_path, 'JPEGImages', image['file_name'])) # 创建XML文件 xml_file = os.path.join(voc_path, 'Annotations', os.path.splitext(image['file_name'])[0] + '.xml') root = ET.Element('annotation') ET.SubElement(root, 'folder').text = 'VOC2012' ET.SubElement(root, 'filename').text = image['file_name'] ET.SubElement(root, 'segmented').text = '0' # 处理每个标注 for annotation in annotations['annotations']: if annotation['image_id'] == image['id']: # 添加对象信息 obj = ET.SubElement(root, 'object') ET.SubElement(obj, 'name').text = annotation['category_id'] ET.SubElement(obj, 'pose').text = 'Unspecified' ET.SubElement(obj, 'truncated').text = '0' ET.SubElement(obj, 'difficult').text = '0' bbox = annotation['bbox'] bndbox = ET.SubElement(obj, 'bndbox') ET.SubElement(bndbox, 'xmin').text = str(bbox[0]) ET.SubElement(bndbox, 'ymin').text = str(bbox[1]) ET.SubElement(bndbox, 'xmax').text = str(bbox[0] + bbox[2]) ET.SubElement(bndbox, 'ymax').text = str(bbox[1] + bbox[3]) # 保存XML文件 tree = ET.ElementTree(root) tree.write(xml_file) # 创建ImageSets/Main/trainval.txt文件 with open(os.path.join(voc_path, 'ImageSets', 'Main', 'trainval.txt'), 'w') as f: for image in annotations['images']: f.write(os.path.splitext(image['file_name'])[0] + '\n') # 将VOC数据集格式复制到COCO数据集所在目录 shutil.copytree(voc_path, os.path.join(coco_path, 'voc_dataset')) ``` 该代码会读取COCO数据集的annotations.json文件,并将其中的每个图像换为VOC数据

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值