Python3使用PIL将图片转换为RGB格式的完整指南

Ryan
Ryan
发布时间:2026-10-13 | 3人浏览过
原创

本文介绍如何利用Python3的PIL库将非RGB格式图片转换为RGB格式,以满足深度学习模型对输入数据的要求。内容涵盖单张图片转换方法及基于txt文件路径列表的批量处理脚本,解决灰度图等格式转换的实际需求。

图片转换背景与需求

感想

在进行深度学习图像处理时,若需自行制作或收集数据集,往往不可避免地对数据进行预处理。由于大多数深度学习模型仅支持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 相关产品和应用

全部下载

专题列表