【问题标题】:Pillow: Cannot Convert 'P' to 'RGB'枕头:无法将“P”转换为“RGB”
【发布时间】:2021-05-05 00:00:02
【问题描述】:

我正在尝试使用 Pillow 将文件夹中的所有图像文件转换为 jpg。

我是枕头新手,所以我不是 100% 掌握这些概念。

以下是我正在使用的功能:

def convert_jpg(file, folder = 'flag_images/', delete = False):
    filepath = folder + file
    print(file)
    img = Image.open(filepath, mode = 'r')
    if delete:
        img.save(folder + 'backup/' + file)
        os.remove(filepath)
    if img.mode != 'RGB':
        img.convert('RBG')
    filepath = filepath[0:-3] + 'jpg'
    img.save(filepath)

def convert_all(folder = 'flag_images/'):
    for filename in os.listdir(os.path.abspath(os.getcwd()) + '/flag_images'):
        if filename[-3:] != 'jpg':
            convert_jpg(file = filename, folder = folder, delete = True)

在运行 convert_all 时,当我进入模式为“P”的文件时出现以下错误:

ValueError                              Traceback (most recent call last)
~/anaconda3/lib/python3.8/site-packages/PIL/Image.py in convert(self, mode, matrix, dither, palette, colors)
   1025         try:
-> 1026             im = self.im.convert(mode, dither)
   1027         except ValueError:

ValueError: conversion not supported

如何成功将模式转换为RGB,以便保存为jpg?

【问题讨论】:

    标签: python image python-imaging-library rgb


    【解决方案1】:

    您有拼写错误和使用错误。你需要改变这个:

    img.convert('RBG')
    

    到这里:

    img = img.convert('RGB')
    

    也就是说,根本没有必要,因为 JPEG 不一定是 P 模式。

    【讨论】:

    • 我在这个编辑中仍然遇到同样的错误。我也不确定您所说的“不应该”是什么意思。我需要将这些 png 文件转换为 jpg,如果不是 RGB 模式,对话会失败。如何将 P 模式转换为 RGB?
    • 没关系-我现在看到了错字。留下评论以适当羞辱。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-14
    • 2019-07-28
    • 1970-01-01
    • 2012-11-04
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    相关资源
    最近更新 更多