说明:排序后命名源自分割测试任务里真值图和原图的一一对应,以计算分割效果。规范命名(eg:000,010,200)也是为了源程序中sort()函数的使用。
使用:tot_path处写要批量命名的文件夹地址,new_tot_path处写命名完成后要转移到的文件夹地址。
注意:.sort()函数的排序方式和natsorted()函数的排序方式是不同的,可以通过print()的方式查看排序规则做好判断。
import os
from PIL import Image
from glob import glob
from natsort import natsorted, ns
tot_path = ''
new_tot_path = ''
os.makedirs(new_tot_path,exist_ok=True)
# path = glob(os.path.join(tot_path,'*.jpg'))
path = os.listdir(tot_path)
path.sort()
# pat = natsorted(path, alg=ns.PATH)
i = 1
for pho in path:
# print(pho)
os.chdir(tot_path)
img = Image.open('./' + pho)
# img2 = img.resize((32 , 32))
if i < 10: # 0-9
newname = "00" + str(i)
elif i > 9 and i < 100: # 10-100
newname = "0" + str(i)
elif i > 99 and i < 1000: # 100-1000
newname = str(i)
img.save(new_tot_path + '/' + newname + '.png')
i = i + 1