Python如何将jpg图像修改大小并转换为png
作者:回炉重造P
这篇文章主要介绍了Python如何将jpg图像修改大小并转换为png问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
Python将jpg图像修改大小并转换为png
简单利用pillow库实现的大小与格式转换的脚本。
实现
import os import PIL.Image as Image def changeJpgToPng(w, h, path): # 修改图像大小 image = Image.open(path) image = image.resize((w, h), Image.ANTIALIAS) # 将jpg转换为png png_name = str(path)[0:-len('.jpg')] + '_min.png' image.save(png_name) print(png_name) # 去白底 image = image.convert('RGBA') img_w, img_h = image.size color_white = (255, 255, 255, 255) for j in range(img_h): for i in range(img_w): pos = (i, j) color_now = image.getpixel(pos) if color_now == color_white: # 透明度置为0 color_now = color_now[:-1] + (0,) image.putpixel(pos, color_now) image.save(png_name) if __name__ == '__main__': t_w = 300 t_h = 150 dic = os.listdir('image') for d in dic: if d.count('.jpg') > 0: changeJpgToPng(t_w, t_h, 'image/' + d)
参考实现了去白底的功能,简单循环对比。
结构
Python批量实现jpg图片修改大小并转换为png(图像通道:RGB,适配KITTI数据集)
# python:批量实现jpg图片修改大小并转换为png # author:zhou jinxing import os import PIL.Image as Image def changeJpgToPng(w, h,srcPath,dstPath): # 修改图像大小 image = Image.open(srcPath) image = image.resize((w, h), Image.ANTIALIAS) # 将jpg转换为png png_name = str(dstPath)[0:-len('.jpg')] + '.png' image.save(png_name) print(png_name) # 去白底 #image = image.convert('RGBA') image = image.convert('RGB') img_w, img_h = image.size #color_white = (255, 255, 255, 255) color_white = (255, 255, 255) for j in range(img_h): for i in range(img_w): pos = (i, j) color_now = image.getpixel(pos) if color_now == color_white: # 透明度置为0 color_now = color_now[:-1] + (0,) image.putpixel(pos, color_now) image.save(png_name) if __name__ == '__main__': t_w = 1242 t_h = 375 #srcPath = '/workspace/tlt-experiments/data_fire/image_2_jpg/' #dstPath = '/workspace/tlt-experiments/data_fire/image_2_png/' srcPath = '/workspace/tlt-experiments/data_fire/012/training/image_2/' dstPath = '/workspace/tlt-experiments/data_fire/012/training/image_2_png/' # filename_list = os.listdir('/workspace/tlt-experiments/data_fire/image_2_jpg') # for d in dic: # if d.count('.jpg') > 0: # changeJpgToPng(t_w, t_h, 'image/' + d) print("开始转换...") filename_list = os.listdir('/workspace/tlt-experiments/data_fire/012/training/image_2') for d in filename_list: if d.count('.png') > 0: changeJpgToPng(t_w, t_h,srcPath + d,dstPath + d) pass print("完成了...")
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。