Python 将图像与PIL合并时的模式不匹配

Python 将图像与PIL合并时的模式不匹配,python,python-imaging-library,Python,Python Imaging Library,我正在传递一个.jpg文件的名称 def split_image_into_bands(filename): img = Image.open(filename) data = img.getdata() red = [(d[0], 0, 0) for d in data] # List Comprehension! green = [(0, d[1], 0) for d in data] blue = [(0, 0, d[2]) for d in da

我正在传递一个.jpg文件的名称

def split_image_into_bands(filename):
    img = Image.open(filename)
    data = img.getdata()
    red = [(d[0], 0, 0) for d in data]  # List Comprehension!
    green = [(0, d[1], 0) for d in data]
    blue = [(0, 0, d[2]) for d in data]

    img.putdata(red)    
    img.save(os.path.splitext(filename)[0] + "_red.jpg")
    img.putdata(green)
    img.save(os.path.splitext(filename)[0] + "_green.jpg")
    img.putdata(blue)
    img.save(os.path.splitext(filename)[0] + "_blue.jpg")

    # Put the 3 images back together
    rimage = Image.new(img.mode, img.size)
    rimage.putdata(red)
    gimage = Image.new(img.mode, img.size)
    gimage.putdata(green)
    bimage = Image.new(img.mode, img.size)
    bimage.putdata(blue)
    # Error on the following line: "ValueError: mode mismatch"
    img = Image.merge(img.mode, (rimage, gimage, bimage))    # Second argument is a tuple
    img.save(os.path.splitext(filename)[0] + "_merged.jpg")

该代码可用于merge函数。然后它抛出一个“ValueError:mode mismatch”

我不确定您想做什么,但它出错了,因为
img.mode
RGB
。这意味着您有3个图像,每个图像中有3个通道,因此当您尝试合并它们时,结果将是一个无人理解的9通道图像

以下是我的做法:

#!/usr/bin/env python3

import os
from PIL import Image

# Open inoput image and ensure RGB, get basename
img = Image.open(filename).convert('RGB')
basename = os.path.splitext(filename)[0]

# Split into 3 bands, R, G and B
R, G, B = img.split()

# Synthesize empty band, same size as original
empty = Image.new('L',img.size)

# Make red image from red channel and two empty channels and save
Image.merge('RGB',(R,empty,empty)).save(basename + "_red.jpg")
# Make green image from green channel and two empty channels and save
Image.merge('RGB',(empty,G,empty)).save(basename + "_green.jpg")
# Make blue image from blue channel and two empty channels and save
Image.merge('RGB',(empty,empty,B)).save(basename + "_blue.jpg")

# Merge all three original RGB bands into new image
Image.merge('RGB',(R,G,B)).save(basename + "_merged.jpg")

我看不出这是如何回答这个问题的。L在哪里应用?所有包含
Image.new()
的行都需要使用类型
L
而不是
RGB
。在我将模式更改为“L”后,运行时错误消失了,但合并的图片都是黑色的。我以后可能有时间帮助您。同时,你能说说把3个频道合并在一起并保存它有什么意义吗?它将和原来的一样。。。你已经有了。