简介

使用Python实现对文件夹内的文件/图片批量重命名,重命名格式为00001.jpg,便于制作数据集

代码实现

完整代码

图片重命名代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import os
from PIL import Image

# Image extension supported.
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp', 'jpeg', 'JPEG'])

def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

def is_valid_image(img_path: str) -> bool:
bvalid = True
try:
Image.open(img_path).verify()
except:
bvalid = False
return bvalid

def rename(img_path: str, index: int) -> None:
filelist = os.listdir(img_path)
total_num = len(filelist)
count = 0
for item in filelist:
if allowed_file(item):
filename_suffix = '.' + item.rsplit('.', 1)[1]
src = os.path.join(os.path.abspath(img_path), item)
dst = os.path.join(os.path.abspath(img_path), '00' + format(str(index), '0>4s') + filename_suffix)
try:
os.rename(src, dst)
print('converting %s to %s' % (src, dst))
index = index + 1
count = count + 1
except:
index = index + 1
continue
print('total %d to rename & converted %d jpgs' % (total_num, count))

if __name__ == '__main__':
img_dir = './output/word'
index = 0
rename(img_dir, index)