PIL库提供了强大的功能,可以将所有格式的彩色或灰度图片读入,并以其他格式保存(真格式,而不是重命名)。
对于彩色图像,不管其图像格式是PNG,还是BMP,或者JPG,在PIL中,使用Image模块的open()函数打开后,返回的图像对象的模式都是“RGB”。
对于灰度图像,不管其图像格式是PNG,还是BMP,或者JPG,打开后,其模式为“L”。
--------------------------------------------------------------------------------
在安装PIL库时,需要注意Python的版本。
pip install PIL #支持的版本为python 2.5, 2.6, 2.7
pip install pillow #支持的版本为python 3.+
代码如下:
# image to png
# 任意格式 to 任意格式
# 修改格式名即可
import os
from PIL import Image
import shutil
import sysdef image2png(dataset_dir,type):files = [] image_list = os.listdir(dataset_dir) files = [os.path.join(dataset_dir, _) for _ in image_list] for index,bmp in enumerate(files): if index > 250: breaktry: sys.stdout.write('\r>>Converting image %d/100000 ' % (index)) sys.stdout.flush() im = Image.open(bmp) png = os.path.splitext(bmp)[0] + "." + typeim.save(png) except IOError as e: print('could not read:',bmp) print('error:',e) print('skip it\n') sys.stdout.write('Convert Over!\n') sys.stdout.flush() if __name__ == "__main__": current_dir = os.getcwd() print(current_dir)data_dir = 'A:\pics' #这里是图片文件夹image2png(data_dir,'png')
如果仅是重命名,可以直接在文件夹中,运行命令行cmd,运行以下命令:
ren .*bmp .*png #仅是重命名而已
之前文章中,对表格数据的处理,对三元组处理,网页元素处理,都是用了Python的集成开源库,看来Python成为新时代宠儿是有道理的,毕竟这是个大数据的时代。
参考文章:
https://blog.csdn.net/icamera0/article/details/50843172/
https://blog.csdn.net/u013517229/article/details/81076705
https://www.jb51.net/article/141625.htm