最近这个制定数据集真让人头大,写一篇博客记录一下配制的过程:
首先下载coco2017数据集,下载下来之后,应该是这样的:
这是含有标注信息的所有文件(80类)。
图像没什么说的,就是图像数据。
然后用下面的代码去将.json文件读取出来,转变为一一对应的.txt标签。
这是train的:
#COCO 格式的数据集转化为 YOLO 格式的数据集
#--json_path 输入的json文件路径
#--save_path 保存的文件夹名字,默认为当前目录下的labels。
import os
import json
from tqdm import tqdm
import argparse
parser = argparse.ArgumentParser()
#这里根据自己的json文件位置,换成自己的就行
parser.add_argument('--json_path', default='/home/zhaoyubing/coco2017/annotations/instances_train2017.json',type=str, help="input: coco format(json)")
#这里设置.txt文件保存位置
parser.add_argument('--save_path', default='/home/zhaoyubing/coco2017/labels/train2017', type=str, help="specify where to save the output dir of labels")
arg = parser.parse_args()
def convert(size, box):
dw = 1. / (size[0])
dh = 1. / (size[1])
x = box[0] + box[2] / 2.0
y = box[1] + box[3] / 2.0
w = box[2]
h = box[3]
#round函数确定(xmin, ymin, xmax, ymax)的小数位数
x = round(x * dw, 6)
w = round(w * dw, 6)
y = round(y * dh, 6)
h = round(h * dh, 6)
return (x, y, w, h)
if __name__ == '__main__':
json_file = arg.json_path # COCO Object Instance 类型的标注
ana_txt_save_path = arg.save_path # 保存的路径
data = json.load(open(json_file, 'r'))
if not os.path.exists(ana_txt_save_path):
os.makedirs(ana_txt_save_path)
id_map = {} # coco数据集的id不连续!重新映射一下再输出!
with open(os.path.join(ana_txt_save_path, 'classes.txt'), 'w') as f:
# 写入classes.txt
for i, category in enumerate(data['categories']):
f.write(f"{category['name']}\n")
id_map[category['id']] = i
# print(id_map)
#这里需要根据自己的需要,更改写入图像相对路径的文件位置。
list_file = open(os.path.join(ana_txt_save_path, 'train2017.txt'), 'w')
for img in tqdm(data['images']):
filename = img["file_name"]
img_width = img["width"]
img_height = img["height"]
img_id = img["id"]
head, tail = os.path.splitext(filename)
ana_txt_name = head + ".txt" # 对应的txt名字,与jpg一致
f_txt = open(os.path.join(ana_txt_save_path, ana_txt_name), 'w')
for ann in data['annotations']:
if ann['image_id'] == img_id:
box = convert((img_width, img_height), ann["bbox"])
f_txt.write("%s %s %s %s %s\n" % (id_map[ann["category_id"]], box[0], box[1], box[2], box[3]))
f_txt.close()
#将图片的相对路径写入train2017或val2017的路径
list_file.write('./images/train2017/%s.jpg\n' %(head))
list_file.close()
这是val的:
import json
from tqdm import tqdm
import argparse
parser = argparse.ArgumentParser()
#这里根据自己的json文件位置,换成自己的就行
parser.add_argument('--json_path', default='/home/zhaoyubing/coco2017/annotations/instances_val2017.json',type=str, help="input: coco format(json)")
#这里设置.txt文件保存位置
parser.add_argument('--save_path', default='/home/zhaoyubing/coco2017/labels/val2017', type=str, help="specify where to save the output dir of labels")
arg = parser.parse_args()
def convert(size, box):
dw = 1. / (size[0])
dh = 1. / (size[1])
x = box[0] + box[2] / 2.0
y = box[1] + box[3] / 2.0
w = box[2]
h = box[3]
#round函数确定(xmin, ymin, xmax, ymax)的小数位数
x = round(x * dw, 6)
w = round(w * dw, 6)
y = round(y * dh, 6)
h = round(h * dh, 6)
return (x, y, w, h)
if __name__ == '__main__':
json_file = arg.json_path # COCO Object Instance 类型的标注
ana_txt_save_path = arg.save_path # 保存的路径
data = json.load(open(json_file, 'r'))
if not os.path.exists(ana_txt_save_path):
os.makedirs(ana_txt_save_path)
id_map = {} # coco数据集的id不连续!重新映射一下再输出!
with open(os.path.join(ana_txt_save_path, 'classes.txt'), 'w') as f:
# 写入classes.txt
for i, category in enumerate(data['categories']):
f.write(f"{category['name']}\n")
id_map[category['id']] = i
# print(id_map)
#这里需要根据自己的需要,更改写入图像相对路径的文件位置。
list_file = open(os.path.join(ana_txt_save_path, 'train2017.txt'), 'w')
for img in tqdm(data['images']):
filename = img["file_name"]
img_width = img["width"]
img_height = img["height"]
img_id = img["id"]
head, tail = os.path.splitext(filename)
ana_txt_name = head + ".txt" # 对应的txt名字,与jpg一致
f_txt = open(os.path.join(ana_txt_save_path, ana_txt_name), 'w')
for ann in data['annotations']:
if ann['image_id'] == img_id:
box = convert((img_width, img_height), ann["bbox"])
f_txt.write("%s %s %s %s %s\n" % (id_map[ann["category_id"]], box[0], box[1], box[2], box[3]))
f_txt.close()
#将图片的相对路径写入train2017或val2017的路径
list_file.write('./images/train2017/%s.jpg\n' %(head))
list_file.close()
这两段代码运行完成后,就可以生成所有的.txt文件类型的标签了。
接着我们提取其中一类的标签(person),person的ID = 0,第一个标签就是person。
运行这段代码,就可以提取出来特定类别的所有数据和标签:
import os
from shutil import copyfile
src_path = '/home/zhaoyubing/coco2017/coco2017-yolo/labels/val2017/' # 标签
img_path = '/home/zhaoyubing/coco2017/coco2017-yolo/images/val2017/' # 图像
dst_label_path = '/home/zhaoyubing/data_person/labels/val/'
dst_img_path = '/home/zhaoyubing/data_person/images/val/'
cls_id = ['0'] # person, 也可以多添加几个类别,提取多个类别的图像和标签
labels = os.listdir(src_path)
labels.sort()
for label in labels:
if label[-1] != 't':
continue
# 存标签
tmp = []
for line in open(src_path + '/' + label):
str_list = line.split()
# 被选类别的标签
for i in range(len(cls_id)):
if str_list[0] == cls_id[i]:
# 改成自己的标签,这里是数组下标
line = str(i) + line[1:]
tmp.append(line)
# 没有被选类别
if len(tmp) < 1:
continue
# 新的标签文件
with open(dst_label_path + label, 'w') as f:
for item in tmp:
f.write(item)
#f.close()
image = label[:-4] + '.jpg'
# 拷贝有被选类别的图片
copyfile(img_path + '/' + image, dst_img_path + image)
等数据集处理好了以后,生成train.txt,val.txt索引文件,以便于后续训练使用。
这里我最后生成的unlabel.txt,读者可自行修改一下。
import os
def generate_txt_file(folder_path, output_file):
with open(output_file, 'w') as f:
for root, dirs, files in os.walk(folder_path):
for filename in files:
if filename.endswith(('.jpg', '.jpeg', '.png', '.bmp')):
image_path = os.path.relpath(os.path.join(root, filename), folder_path)
f.write('./data_person/unlabel_images/' + image_path + '\n')
# 指定图像文件夹路径和输出文件路径
folder_path = '/home/zhaoyubing/data_person/unlabel_images' # 图像文件夹路径
output_file = 'unlabel.txt' # 输出文件名
# 生成txt文件
generate_txt_file(folder_path, output_file)