是否可以在Python中更改单个像素的颜色?

rec*_*gle 19 python pixel python-imaging-library

我需要python来改变图片上一个像素的颜色,我该怎么做呢?

sso*_*low 22

基于Gabi Purcaru 链接中给出的示例,这里有一些从PIL文档拼凑而成的东西.

使用PIL可靠地修改单个像素的最简单方法是:

x, y = 10, 25
shade = 20

from PIL import Image
im = Image.open("foo.png")
pix = im.load()

if im.mode == '1':
    value = int(shade >= 127) # Black-and-white (1-bit)
elif im.mode == 'L':
    value = shade # Grayscale (Luminosity)
elif im.mode == 'RGB':
    value = (shade, shade, shade)
elif im.mode == 'RGBA':
    value = (shade, shade, shade, 255)
elif im.mode == 'P':
    raise NotImplementedError("TODO: Look up nearest color in palette")
else:
    raise ValueError("Unexpected mode for PNG image: %s" % im.mode)

pix[x, y] = value 

im.save("foo_new.png")
Run Code Online (Sandbox Code Playgroud)

这将适用于PIL 1.1.6及更高版本.如果您不得不支持旧版本,那么您可以牺牲性能并替换pix[x, y] = valueim.putpixel((x, y), value).