使用 PIL 获取像素的 RGB [英] Get pixel's RGB using PIL
问题描述
是否可以使用 PIL 获取像素的 RGB 颜色?我正在使用此代码:
Is it possible to get the RGB color of a pixel using PIL? I'm using this code:
im = Image.open("image.gif")
pix = im.load()
print(pix[1,1])
然而,它只输出一个数字(例如 0
或 1
)而不是三个数字(例如 60,60,60
for R,G,B).我想我不了解该功能.我想要一些解释.
However, it only outputs a number (e.g. 0
or 1
) and not three numbers (e.g. 60,60,60
for R,G,B). I guess I'm not understanding something about the function. I'd love some explanation.
非常感谢.
推荐答案
是的,这样:
im = Image.open('image.gif')
rgb_im = im.convert('RGB')
r, g, b = rgb_im.getpixel((1, 1))
print(r, g, b)
(65, 100, 137)
您之前使用 pix[1, 1]
获得单个值的原因是因为 GIF 像素指的是 GIF 调色板中的 256 个值之一.
The reason you were getting a single value before with pix[1, 1]
is because GIF pixels refer to one of the 256 values in the GIF color palette.
另见此 SO 帖子:Python 和 PILGIF 和 JPEG 的像素值不同 并且此 PIL 参考页面包含有关convert()
函数.
See also this SO post: Python and PIL pixel values different for GIF and JPEG and this PIL Reference page contains more information on the convert()
function.
顺便说一下,您的代码对于 .jpg
图像也能正常工作.
By the way, your code would work just fine for .jpg
images.
这篇关于使用 PIL 获取像素的 RGB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!