在进行数据集扩充训练,会有 聚合相似图片 这一任务
一个品类至少上千种不同商品,比如 白酒 、葡萄酒
在聚合几百张时,就会忘记之前已经聚合过,一个文件夹一个文件夹找很浪费时间
提取一张基准图就很有必要了
- 功能:
- 删除混杂在图片中的 txt 和 temp 文件
- 遍历文件夹,从每个文件夹提取一张图片移至新目录
- 移动的图片重命名 命名格式为: 文件夹名+——+图片名(—— 分隔文件夹与图片名,按F2时,可以快速复制文件夹名)
- 删除空文件夹
- 显示图片索引数量,图片多时可以改成 index % 100 == 0
- 注意:判断文件是否为空,这里不能只使用
len(files) == 0
。如果目录写错,为该目录的上一级目录,会把有文件的文件夹删除。
# -*- coding: utf-8 -*-
import os
import shutil
import random
def del_suffix(root_path,suffix):
dir_list = os.listdir(root_path)
for dir_name in dir_list:
dir_path = os.path.join(root_path, dir_name)
for root, dirs, files in os.walk(dir_path):
for txt_file in files:
exts = suffix.split(' ')
for ext in exts:
if txt_file.lower().endswith(ext):
os.remove(os.path.join(root, txt_file))
def select_img(root_path):
#判断目录文件夹是否存在
if(not os.path.exists(root_path)):
print("the path not exist!")
return
root_new_img = root_path + '_move'
#判断目录文件夹是否已经存在
if os.path.exists(root_new_img):
print('the new folder is exist!')
#删除已存在的目录文件夹
shutil.rmtree(root_new_img)
#构建新的文件夹
os.mkdir(root_new_img)
dir_list = os.listdir(root_path)
#把可遍历的列表组合为索引序列,从1开始计数
for (index, dir_name) in enumerate(dir_list, start=1):
dir_path = os.path.join(root_path, dir_name)
if os.path.isdir(dir_path):
for root, dirs, files in os.walk(dir_path):
#如果文件夹为空,且文件夹下面不包含任何内容,则删除该文件夹
if os.path.isdir(root) and len(os.listdir(root)) == 0 and len(files) == 0:
shutil.rmtree(dir_path)
continue
if len(files) != 0:
#随机选取一个文件
chose_img = random.sample(files, 1)[0]
chose_img_path = os.path.join(dir_path, chose_img)
#选取的图片保留文件夹名称
chose_img_newname = '{0}————{1}'.format(dir_name,chose_img)
new_img_path = os.path.join(root_new_img, chose_img_newname)
shutil.copy(chose_img_path, new_img_path)
else:
#文件夹外面的图片
continue
if index % 1 == 0:
print('the {0} img is done'.format(index))
if __name__ == "__main__":
root_path = r'D:\0text'
suffix = '.txt .temp'
del_suffix(root_path,suffix)
select_img(root_path)