Python如何将jpg图像修改大小并转换为png
更新时间:2023年09月11日 15:21:54 作者:回炉重造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("完成了...")总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
如何测试Python网站的访问速度,并且优化Python网站的性能
本文使用网络工具和Python测速库进行测试Python网站的访问速度,通过优化代码性能和优化服务器性能以及优化数据库性能等有针对性地优化Python网站的性能2024-01-01
Python中实现 xls 文件转 xlsx的4种方法(示例详解)
在 Python 中,可以采用 pandas、pyexcel、win32com 和 xls2xlsx 这四个模块,实现 xls 转 xlsx 格式,本文以 Excel 示例文件test_Excel.xls 为例结合示例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧2024-06-06
pytorch中获取模型input/output shape实例
今天小编就为大家分享一篇pytorch中获取模型input/output shape实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2019-12-12


最新评论