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实现哈希表、字典、集合操作

哈希表 哈希表(Hash Table, 又称为散列表),是一种线性表的存储结构。哈希表由一个直接寻址表和一个哈希函数组成。哈希函数h(k)将元素关键字k作为自变量,返回元素的存储下标。...

pytorch中的上采样以及各种反操作,求逆操作详解

pytorch中的上采样以及各种反操作,求逆操作详解

import torch.nn.functional as F import torch.nn as nn F.upsample(input, size=None, scale_fact...

在Python中关于中文编码问题的处理建议

字符串是Python中最常用的数据类型,而且很多时候你会用到一些不属于标准ASCII字符集的字符,这时候代码就很可能抛出UnicodeDecodeError: 'ascii' codec...

python实现基于朴素贝叶斯的垃圾分类算法

python实现基于朴素贝叶斯的垃圾分类算法

一、模型方法        本工程采用的模型方法为朴素贝叶斯分类算法,它的核心算法思想基于概率论。我们称之为“朴素”,是因为整个形式化过程只做最原...

tensorflow实现简单的卷积神经网络

本文实例为大家分享了Android九宫格图片展示的具体代码,供大家参考,具体内容如下 一.知识点总结 1.  卷积神经网络出现的初衷是降低对图像的预处理,避免建立复杂...