因为准备训练keras-yolo3,开源代码上给出了voc_annotation.py文件,只要将自己的数据格式处理成PASCAL VOC格式,那么运行voc_annotation.py就可以将自己的数据集处理成模型需要的数据集。
现在我的标注数据格式如下(CSV文件,第一列是文件名,第二列对应bbox):
图片是文件:
不管如何先写一个读写CSV文件的脚本utils.py:
# -*- coding: utf-8 -*-
# @Author : matthew
# @File : utils.py
# @Software: PyCharm
import csv
import os
def read_csv(csv_path, pre_dir):
'''
:param csv_path:csv文件路径
:param pre_dir: 图片数据所在的文件夹
:return:
'''
label_dict = {}
with open(csv_path, "r") as f:
reader = csv.reader(f)
header = True
for line in reader:
# 除去文件头
if header:
header = False
continue
# 处理文件存储路径,当做标签
image_path = os.path.join(pre_dir, line[0])
# 处理后面的bbox
bbox = []
if line[1] is not None and len(line[1].strip()) > 0:
for i in line[1].split(';'):
if i is not None and len(i.strip()) > 0:
bbox.append(list(map(lambda x: round(float(x.strip())), i.split('_'))))
# 添加到label_dict
label_dict.setdefault(image_path, bbox)
return label_dict
def write_csv(result_dict, out_path='out.csv'):
'''
:param result_dict: 只一个图片路径,对应存储相应bbox的list的字典
:param out_path:
:return:
'''
with open(out_path, 'w', newline='') as f:
writer = csv.writer(f)
# 写文件头
writer.writerow(['name', 'coordinate'])
for image in result_dict.keys():
image_name = os.path.split(image)[-1]
bbox = result_dict.get(image, [])
bbox_rs = ';'.join(['_'.join(str(int(id)) for id in i) for i in bbox])
writer.writerow([image_name, bbox_rs])
if __name__ == '__main__':
label_dict = utils.read_csv(csv_path=r'./train_b.csv',
pre_dir=r'/home/matthew/dataset')
write_csv(label_dict)
下面开始正式制作数据集!
第一步:改名
VOC标准数据集中图片名称是“000001.jpg”都为6-9位数字,jpg格式的。
因为是第一次制作,以为这种命名是必须的,我看网上也有不少人说要改名的问题。(制作完毕后,发现这一步是大可不必的,所以想省就省了吧。)
为了规范,还是进行了改名操作。