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实现图片添加文字

在工作中有时候会给图上添加文字,常用的是PS工具,不过我想通过代码的方式来给图片添加文字。 需要使用的Python的图像库:PIL.更加详细的知识点如下: Imaga模块:用来创建,打开...

使用Python实现windows下的抓包与解析

使用Python实现windows下的抓包与解析

系统环境:windows7,选择windows系统是因为我对自己平时日常机器上的流量比较感兴趣 python环境:python2.7 ,这里不选择python3的原因,是因为接下来要用到...

在Python 字典中一键对应多个值的实例

如下所示: #encoding=utf-8 print '中国' #字典的一键多值 print'方案一 list作为dict的值 值允许重复' d1={} key=1...

django实现前后台交互实例

django实现前后台交互实例

本文介绍了django实现前后台交互实例,分享给大家,希望对大家有所帮助 准备工作: 前端框架:AngularJS+bootstap 数据库:sqlite3 前端代码: inde...

解决python2.7用pip安装包时出现错误的问题

解决python2.7用pip安装包时出现错误的问题

最近在使用pip安装包的的时候出现下面错误 UnicodeEncodeError: 'ascii' codec can't encode character u'\u258f'...