gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:54:37 26 4
gpt4 key购买 nike

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

最佳答案

以 Gabi Purcaru 的 link 中给出的示例为基础,这是从 PIL docs 拼凑而成的东西.

使用 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")

这适用于 PIL 1.1.6 及更高版本。如果你运气不好不得不支持旧版本,你可以牺牲性能并将 pix[x, y] = value 替换为 im.putpixel((x, y), value ).

关于python - 是否可以在 Python 中更改单个像素的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3596433/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com