Python | 批量更改图像尺寸到统一大小(修改版)

功能

Faster r_cnn 训练神经网络时,从GitHub上clone作者的代码,并创建了自己的数据库。但是由于源代码中输入的图像的大小有一定的限制,一般在500-750之间, 自己创建的图像数据库中图像过大,因此用python 批量更改图像尺寸到统一大小。

从CSDN上找到了一段代码(原网址为:https://blog.csdn.net/atyzy/article/details/77905463 ),但是这段代码在运行的时候会报错,导致部分生成的图像无法打开。对其进行了修改,修改后的代码如下所示。

错误分析:”‘P’,’RGBA’,’RGB’这是PIL Image读图可能出现的三种mode,每种mode的图片数据都有不同的组织形式

修改部分功能为:将读图的mode全部转换为“RGB“。

修改后的代码(python)

from PIL import Image
import os.path
import glob
def convertjpg(jpgfile,outdir,width=500,height=500):
    img=Image.open(jpgfile)
    try:
        new_img = img.resize((width, height), Image.BILINEAR)
        if new_img.mode == 'P':
            new_img = new_img.convert("RGB")
        if new_img.mode == 'RGBA':
            new_img = new_img.convert("RGB")
        new_img.save(os.path.join(outdir, os.path.basename(jpgfile)))
    except Exception as e:
        print(e)

for jpgfile in glob.glob("G:/my/Process_recent/python/Image_database/figure/spacecraft/*.jpg"):
    # print(jpgfile)
    convertjpg(jpgfile,"G:/my/Process_recent/python/Image_database/figure/spacecraft_unifsize")

评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值