图像预处理之PNG与JPG互转

在做AI的时候,会有图像的解码的问题,有些框架或者是算法不支持PNG格式的图片反之亦然,导致训练的时候会出现图像解码失败的情况。下面是png和jpg互转的脚本,记录下:
jpg2png:

from PIL import Image
import os
def convert_to_png(image_path, output_path):
    image = Image.open(image_path)
    os.makedirs(os.path.dirname(output_path), exist_ok=True)
    image.save(output_path, 'PNG')
    print(f"已将图片 {image_path} 转换为PNG格式,并保存为 {output_path}")

# # 使用示例
# convert_to_png("image.jpg", "image.png")

image_path = 'test/good'
image_out = 'test/good_n'
os.makedirs(image_out, exist_ok=True)
image_list = os.listdir(image_path)

for file in image_list:
    img_path = os.path.join(image_path, file)
    name, ext = file.rsplit('.')
    name = name + '.png'
    img_out = os.path.join(image_out, name)
    convert_to_png(img_path, img_out)

png2jpg

import os
from PIL import Image
filePath = '../data/input/peta/image'
jpg_name = os.listdir(filePath)

if __name__ == '__main__':
    # Convert PNG format pictures to JPG format pictures
    path = filePath + 's/'
    if os.path.exists(path):
        pass
    else:
        os.mkdir(path)
    for name in jpg_name:
        im = Image.open('../data/input/peta/image/' + name)
        im = im.convert('RGB')
        im.save('../data/input/peta/images/' + name[0:5] + '.jpg', quality=95)
        print(name[0:5])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值