我正在传递 .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")
该代码适用于合并功能。然后它抛出“ValueError:模式不匹配”
我不确定你想做什么,但它出了问题,因为img.mode
is 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")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)