Python递归批量重命名文件
通过递归把指定的path按照dict中的键值对,将文件名中的键用对应的值替换。
import os
def test(path, dict):
"""
递归把指定的path按照dict中的键值对,将文件名中的键用对应的值替换。
"""
if os.path.isdir(path):
for child in os.listdir(path):
for k, v in dict.items():
if child.find(k) > 0:
old = path + child
child = child.replace(k, v)
new = path + child
print(old, new)
os.renames(old, new)
if os.path.isdir(path + child):
child_path = path + child + '/'
test(child_path, dict)
if __name__ == "__main__":
path = './test_dataset/'
ch_to_en_dict = {
'红': 'red',
'橙': 'orange',
'黄': 'yellow',
'绿': 'green',
'青': 'cyan',
'蓝': 'blue',
'紫': 'purple'
}
test(path, ch_to_en_dict)
随笔-Python批量调整图片大小
自己的数据集比较凌乱,图片大小不一,可以通过Python批量来调整图片大小为统一尺寸,方便训练。
import os
from PIL import Image
def resize(old_path, new_path, size, resample):
"""
通过指定的resample方式调整old_path下所有的jpg图片为指定的size,并保存到new_path下
"""
if os.path.isdir(old_path):
for child in os.listdir(old_path):
if child.find('.jpg') > 0:
im = Image.open(old_path + child)
im_resized = im.resize(size=size, resample=resample)
if not os.path.exists(new_path):
os.makedirs(new_path)
print(child, 'resize successfully!')
im_resized.save(new_path + child, im.format)
child_path = old_path + child + '/'
resize(child_path, new_path, size, resample)
if __name__ == "__main__":
old_path = './test_dataset/'
new_path = './test_dataset_train/'
size = (1280, 720)
resample = Image.BILINEAR # 使用线性插值法重采样
resize(old_path, new_path, size, resample)
本文内容不用于商业目的,如涉及知识产权问题,请权利人联系51Testing小编(021-64471599-8017),我们将立即处理