VOC数据批量按txt文件当中的图片路径进行imgs和xml文件的分类提取
voc数据集下载
这个包含了12年和07年的
链接: voc2012and2007数据集
提取自己所需要的类的正样本放在一个文件夹里面
主要是为了剔除负样本保留正样本
代码如下
按照注释更改所需要的类别和路径
import os
import shutil
#建立新的txt文件
def create_txt(path,dstpath):
file_name_set = set()
with open(path, 'r') as f:
# 读取文本每一行
txt_line_list = f.readlines()
for l in txt_line_list:
# 判断标号图片是否为所需分类
if not l.endswith('-1\n') and not l.endswith('0\n'):
f_list = l.split()
# 获取图片文件名
file_name = f_list[0]
# 将所需文件名放入集合中之后使用
file_name_set.add(file_name)
f.close()
print(len(file_name_set), 'files.')
with open(dstpath, 'a') as f:
for i in file_name_set:
f.write(i+'\n')
f.close()
# 读取目标txt文件
def read_txt(path):
file_name_set = set()
with open(path, 'r') as f:
# 读取文本每一行
txt_line_list = f.readlines()
for l in txt_line_list:
# 判断标号图片是否为所需分类
if not l.endswith('-1\n') and not l.endswith('0\n'):
f_list = l.split()
# 获取图片文件名
file_name = f_list[0]
# 将所需文件名放入集合中之后使用
file_name_set.add(file_name)
print(len(file_name_set), 'files.')
f.close()
img_set = set()
label_set = set()
for i in file_name_set:
# 将文件名组合成图片和标签名
img_name = str(i) + '.jpg'
label_name = str(i) + '.xml'
# 放入相应集合中
img_set.add(img_name)
label_set.add(label_name)
return img_set, label_set
# 用于对文件从原路径复制到目标路径
def copy_file(src_path, dst_path):
if not os.path.exists(dst_path):
print('Make the target dataset directory.')
os.mkdir(dst_path)
if os.path.exists(src_path):
# 复制使用函数
shutil.copy(src_path, dst_path)
else:
print(src_path, 'is not exist!')
# 目标路径
dst_sample_path_imgs = 'C:/Users/PaulY/Desktop/testdata/VOC/JPEGImages'
dst_sample_path_xml = 'C:/Users/PaulY/Desktop/testdata/VOC/Annotations'
# 原始数据分类的txt路径
txt_path = './VOCdevkit/VOC2012/ImageSets/Main/'
#所要的类别
classes = ['bicycle', 'bus', 'car', 'motorbike', 'person']
print(classes)
#新分类txt路径 都写在一个里面
dstpath = 'C:/Users/PaulY/Desktop/testdata/VOC/ImageSets/Main/trainval.txt'
#原路径
images_path = './VOCdevkit/VOC2012/JPEGImages'
labels_path = './VOCdevkit/VOC2012/Annotations'
for cl in classes:
txt_path1 = txt_path + cl +'_trainval.txt'
print(txt_path1)
# 获取图片和标签的名称集合
images_set = read_txt(txt_path1)[0]
labels_set = read_txt(txt_path1)[1]
create_txt(txt_path1, dstpath)
print('Start ...')
for img in images_set:
src_img_path = os.path.join(images_path, img)
# 对每一张图片复制
copy_file(src_img_path, dst_sample_path_imgs)
sss = 0
for img in labels_set:
sss += 1
src_label_path = os.path.join(labels_path, img)
# 对每一个标签文件复制
copy_file(src_label_path, dst_sample_path_xml)
print(sss, 'for', len(labels_set))
print('Finished!')
参考
https://blog.csdn.net/guaguablue/article/details/102818570