Mode Mismatch when merging images with PIL

删除回忆录丶 提交于 2021-01-28 02:06:24

问题


I am passing the name of a .jpg file.

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")

The code works up to the merge function. Then it throws a "ValueError: mode mismatch"


回答1:


I'm not sure what you are trying to do, but it is going wrong because img.mode is RGB. That means you have 3 images with 3 channels in each, so when you try to merge them, the result will be a 9-channel image which nobody understands.

Here's how I would approach it:

#!/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")


来源:https://stackoverflow.com/questions/60352546/mode-mismatch-when-merging-images-with-pil

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!