问题描述
是否可以使用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
。我想我不了解这个功能。我想要一些解释。
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帖子:此包含有关 convert()的更多信息
function。
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!