我需要python来改变图片上单个像素的颜色,我该怎么做呢?
发布于 2010-08-31 13:38:15
为了建立在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和更高版本中工作。如果你运气不好,不得不支持一个旧版本,你可以牺牲性能,用im.putpixel((x, y), value)
取代pix[x, y] = value
。
https://stackoverflow.com/questions/3596433
复制相似问题