python3用PIL把图片转换为RGB图片

感想

我们在做深度学习处理图片的时候,如果是自己制作或者收集的数据集,不可避免的要对数据集进行处理,然后大多数模型都只支持RGB格式的图片,这个时候,我们需要把其他格式的图片,例如灰度图像转换为RGB的图片,网上只有灰度图像转换为RGB的教程,我这里弥补一下空缺。

from PIL import Image
import numpy as np
L_path='train/5509031.jpg'
L_image=Image.open(L_path)
out = L_image.convert("RGB")
img=np.array(out)
print(out.mode)
print(out.size)
print(img.shape)

然后就可以转换了哈。

如果是大量的图片呢,那就笨办法,用循环判断吧:

from PIL import Image
from tqdm import tqdm
import numpy as np
root_path='data'
for item in tqdm(examples):
    arr=item.strip().split('*')
    img_name=arr[0]
    image_path=os.path.join(root_path,img_name)
    img=Image.open(image_path)
    if(img.mode!='RGB'):
        img = img.convert("RGB")
        img=np.array(img)
        print(img_name)
        print(img.shape)
    # add your code

我的图片路径是通过一个txt文件读取的,这里给出一些train.txt里面样例:

train/1769512.jpg* postcard construction 67 mixed media epoxy collage 7 x 135 x 4* art||drawing||sculpture
train/5020991.jpg* en el cuadro de honor de todas las 50appsalud en un grfico en espaol* mhealth
train/3525659.jpg* information mogadishu port expansion turkish company* somalia

参考文献

[1].Convert png to jpeg using Pillow in python.https://stackoverflow.com/questions/43258461/convert-png-to-jpeg-using-pillow-in-python

[2].Image Module.https://pillow.readthedocs.io/en/3.1.x/reference/Image.html

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值