python3用PIL把图片转换为RGB图片的实例

yipeiwu_com5年前Python基础

感想

我们在做深度学习处理图片的时候,如果是自己制作或者收集的数据集,不可避免的要对数据集进行处理,然后大多数模型都只支持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

以上这篇python3用PIL把图片转换为RGB图片的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python实现连连看辅助之图像识别延伸

python实现连连看辅助–图像识别延伸(百度AI),供大家参考,具体内容如下 百度AI平台提供图片相似检索API接口,并有详细的API文档说明,可以更好的实现图片识别。 from...

Python-Flask:动态创建表的示例详解

今天小编从项目的实际出发,由于项目某一个表的数据达到好几十万条,此时数据的增删查改会很慢;为了增加提高访问的速度,我们引入动态创建表。 代码如下: from app_factory...

Python 如何优雅的将数字转化为时间格式的方法

将数字转化成时间格式 from dateutil.parser import parse a=20170825 b=str(a) c=parse(b) print(c) 20...

Python安装第三方库及常见问题处理方法汇总

源码安装 Python第三方库几乎都可以在github或者 pypi上找到源码。源码包格式大概有zip 、 tar.zip、 tar.bz2。解压这些包,进入解压好的文件夹,通常会有一个...

详解python中executemany和序列的使用方法

详解python中executemany和序列的使用方法 一 代码 import sqlite3 persons=[ ("Jim","Green"), ("Hu","...