Is it possible to change the color of one individual pixel in Python?

廉价感情. 提交于 2019-12-17 19:57:33

问题


I need python to change the color of one individual pixel on a picture, how do I go about that?


回答1:


To build upon the example given in Gabi Purcaru's link, here's something cobbled together from the PIL docs.

The simplest way to reliably modify a single pixel using PIL would be:

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] = value with im.putpixel((x, y), value).



来源:https://stackoverflow.com/questions/3596433/is-it-possible-to-change-the-color-of-one-individual-pixel-in-python

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