【Python】图片格式转换及尺寸调整

今天跑深度学习时因为数据集的图片尺寸和代码不一致,反向传播时出现某一层输入和输出的格式对不上一直报错,没搞明白代码怎么改,直接调整了图片尺寸去适配代码,顺便做一下笔记。

png转jpg

from PIL import Image
import os
import re


def png2jpg(png_file_path, jpg_dir_path):
    infile = png_file_path

    img = Image.open(infile)
    image_name = re.sub(r'png|PNG$', 'jpg', re.sub(r'.*[/\\]', '', png_file_path))
    outfile = jpg_dir_path + image_name
    if not os.path.exists(jpg_dir_path):
        os.makedirs(jpg_dir_path)

    try:
        if len(img.split()) == 4:
            # prevent IOError: cannot write mode RGBA as BMP
            r, g, b, a = img.split()
            img = Image.merge("RGB", (r, g, b))
            # quality表示图片质量,1最差,95最佳,设置为100会导致部分jpg压缩算法不执行
            img.convert('RGB').save(outfile, quality=95) 
        else:
            img.convert('RGB').save(outfile, quality=95)
        return outfile
    except Exception as e:
        print("PNG转换JPG 错误", e)

像素大小调整

from PIL import Image
import os
import re


def resize_image(image_path, output_dir, w, h):
    image_name = re.sub(r'.*[/\\]', '', image_path)
    outfile = output_dir + image_name
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    img = Image.open(image_path)
    img.resize((w, h), Image.ANTIALIAS).save(outfile, quality=95)

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值