Python 实操 图像重命名与移动
背景
在做深度学习项目过程中,会用到很多图片,图片的来源也多种多样。有一种情况如下:
使用格式工厂
将采集到的现场视频转换成图片,所有的图片分布在视频名对应的文件夹中,如果有几百个视频,那么生成的图片文件夹也有几百个(并且不同文件夹下文件名可能相同,所以不能简单的复制粘贴)。手动去操作太麻烦了。
先上代码,先干为敬。
findimgsmovenew.py
import os
import shutil
root_dir = r"E:\视频"
new_dir = r"E:\视频图片"
project_name = "hcd"
# 图像文件的后缀,自己可新增
imgsuffixlist = ['jpg', 'png', 'jpeg', 'bmp']
startim_idx = 0
# 递归找到文件夹中的文件及子文件夹中的文件
def find_files(root_path: str, abs_file_fullpath: list):
"""
find_files 递归找到文件夹中的文件及子文件夹中的文件
_extended_summary_
Args:
root_path (_type_): 要找的根目录
abs_file_fullpath (_type_): 返回的文件绝对路径
Returns:
_type_: _description_
"""
# 首先遍历当前目录所有文件及文件夹
file_list = os.listdir(root_path)
# 准备循环判断每个元素是否是文件夹还是文件,是文件的话,把名称传入list,是文件夹的话,递归
for file in file_list:
# 利用os.path.join()方法取得路径全名,并存入cur_path变量,否则每次只能遍历一层目录
cur_path = os.path.join(root_path, file)
# 判断是否是文件夹
# 文件夹则递归扫描
# 文件则传入列表中
if os.path.isdir(cur_path):
find_files(cur_path, abs_file_fullpath)
else:
abs_file_fullpath.append(cur_path)
return abs_file_fullpath
def find_image_files(root_dir: str):
files_list = find_files(root_dir, [])
images_list = []
for file in files_list:
if file.split('.')[-1] in imgsuffixlist:
# print(file)
images_list.append(file)
return images_list
def move_to_newfolder(root_dir: str, newfolder: str):
images_list = find_image_files(root_dir)
if os.path.exists(newfolder):
print("文件夹已存在")
else:
os.makedirs(newfolder)
imgidx = startim_idx
for image_name in images_list:
imgsuffix = image_name.split('.')[-1]
# 重命名图像文件,因为内部有些文件有空格和中文字符等,防止后续使用会出现问题
# new_name_last = image_name.split('\\')[-2].replace(" ", '_') + '_' + image_name.split('\\')[-1]
# 也可以直接用序号重命名,这样可能会更好一点
imgidx += 1
new_name_last = project_name + '_' + str(imgidx) + ".jpg"
new_name = os.path.join(newfolder, new_name_last)
print(new_name)
shutil.copy(image_name, new_name)
if __name__ == "__main__":
# find_image_files(root_dir)
move_to_newfolder(root_dir, new_dir)
# pass