Python:PIL模块中的颜色带

0 投票
1 回答
1945 浏览
提问于 2025-04-15 17:30

我有一段来自PIL手册的代码,但我遇到了一个错误信息。

from PIL import Image, ImageEnhance, ImageChops

im = Image.open("D:\\Python26\\PYTHON-PROGRAMME\\bild.jpg")

# split the image into individual bands
source = im.split()

R, G, B = 0, 1, 2

# select regions where red is less than 100
mask = source[R].point(lambda i: i < 100 and 255)

# process the green band
out = source[G].point(lambda i: i * 0.7)

# paste the processed band back, but only where red was < 100
source[G].paste(out, None, mask)

# build a new multiband image
im = Image.merge(im.mode, source)
im = im.point(lambda i: expression and 255)

im.save("D:\\Python26\\PYTHON-PROGRAMME\\bild2.jpg")
print('done')

错误:

Traceback (most recent call last):
  File "D:\Python26\PYTHON-PROGRAMME\00000000000000000", line 14, in <module>
    out = source[G].point(lambda i: i * 0.7)
IndexError: tuple index out of range

1 个回答

3

我这段代码在彩色图片上运行得很好。

如果你在处理只有一个颜色通道的图片,比如黑白JPEG格式的图片,可能会遇到你提到的那个错误。你可以试试在使用split之前,先用im= im.convert('RGB')把图片转换成RGB格式,这样就能确保没问题了。

撰写回答