是否可以在 Python 中更改单个像素的颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3596433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to change the color of one individual pixel in Python?
提问by rectangletangle
I need python to change the color of one individual pixel on a picture, how do I go about that?
我需要 python 来更改图片上单个像素的颜色,我该怎么做?
回答by ssokolow
To build upon the example given in Gabi Purcaru's link, here's something cobbled together from the PIL docs.
为了以 Gabi Purcaru 的链接中给出的示例为基础,这里有一些从PIL 文档拼凑而成的内容。
The simplest way to reliably modify a single pixel using PIL would be:
使用 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")
That will work in PIL 1.1.6 and up. If you have the bad luck of having to support an older version, you can sacrifice performance and replace pix[x, y] = valuewith im.putpixel((x, y), value).
这将适用于 PIL 1.1.6 及更高版本。如果您不幸不得不支持旧版本,则可以牺牲性能并替换pix[x, y] = value为im.putpixel((x, y), value).

