jpg、png、bmp三种类型图像格式转换python
1、使用的语言
python
2、依赖库
pip install tensorflow
pip install keras
3、执行代码
import os
import os.path as osp
from keras.preprocessing.image import load_img
'''
JPG, PNG, BMP three types of image conversion
# @author: qihaoma
# @time: 2022.4.22.11.50.35
'''
class ImageTypeConvert():
'''
data_dir : The directory where the image data to be converted
output_dir : The directory where the converted data is stored
old_type : Image type before conversion------Supported formats: jpg、png、bmp
new_type : Converted image type------Supported formats: jpg、png、bmp
'''
def __init__(self , data_dir , output_dir , old_type , new_type):
self.data_dir = data_dir
self.output_dir = output_dir
if old_type not in ['png','jpg','bmp']:
raise ValueError("{} : The Picture Type is not support.".format(old_type))
if new_type not in ['png','jpg','bmp']:
raise ValueError("{} : The Picture Type is not support.".format(new_type))
self.old_type = old_type
self.new_type = new_type
def excuteConvert(self):
if not os.path.exists(self.output_dir):
os.makedirs(self.output_dir)
filenames = os.listdir(self.data_dir)
for i in range(len(filenames)):
img_path = osp.join(self.data_dir,filenames[i])
img = load_img(img_path)
name = filenames[i].split('.{}'.format(self.old_type))[0]
img.save(os.path.join(self.output_dir,name+'.'+self.new_type))
print('{} images have been converted!'.format(i+1))
if __name__ == '__main__':
png_image_dir = ''
jpg_image_dir = ''
imageTypeConvert = ImageTypeConvert(png_image_dir,jpg_image_dir,'png','jpg')
imageTypeConvert.excuteConvert()
|