转换图片名
# -*- coding: utf-8 -*-
import os
class Rename():
"""
批量重命名文件夹中的图片文件
"""
def __init__(self):
self.path = './train_img' # 需要命名处理的文件夹
self.new_path = './train_img' # 图片处理后保存的文件夹,这里选择同一文件夹
def rename(self):
filelist = os.listdir(self.path) # 获取文件路径
total_num = len(filelist) # 获取文件长度(个数)
i = 1
for item in filelist:
if item.endswith('.jpg'): # 初始图片格式为jpg格式的
src = os.path.join(os.path.abspath(self.path), item)
dst = os.path.join(os.path.abspath(self.new_path), '' + str(i) + '.jpg') # 处理后的格式也为jpg格式,可自定义格式(注:只改后缀名可能格式不会改变)
dst = os.path.join(os.path.abspath(self.path),
'img' + format(str(i), '0>3s') + '.jpg') # 命名格式为img000.jpg形式,可自定义
try:
os.rename(src, dst)
print('converting %s to %s ...' % (src, dst))
i = i + 1
except:
continue
print('total %d to rename & converted %d jpgs' % (total_num, i))
if __name__ == '__main__':
demo = Rename()
demo.rename()
转换图片格式(.jpg)
# -*- coding: utf-8 -*-
import PIL.Image as Image
import os
def start(Path): # Path为文件路径
filelist = os.listdir(Path)
for file in filelist:
print(file)
img = Image.open(Path+ file).convert('RGB')
# print(img)
img.save(Path + file)
print('Done!')
if __name__ == '__main__':
start(path)