[英]Get pixel's RGB using PIL
是否可以使用 PIL 获取像素的 RGB 颜色? 我正在使用这段代码:
im = Image.open("image.gif")
pix = im.load()
print(pix[1,1])
但是,它只输出一个数字(例如0
或1
)而不是三个数字(例如 R、G、B 的60,60,60
)。 我想我不了解该功能。 我想要一些解释。
非常感谢。
是的,这样:
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 个值之一。
另请参阅此 SO 帖子: GIF 和 JPEG 的 Python 和 PIL 像素值不同,此PIL 参考页面包含有关convert()
函数的更多信息。
顺便说一下,您的代码对.jpg
图像来说工作得很好。
用麻木的:
im = Image.open('image.gif')
im_matrix = np.array(im)
print(im_matrix[0][0])
给出位置 (0,0) 处像素的 RGB 向量
GIF 将颜色存储为调色板中 x 种可能颜色之一。 阅读有关gif 有限调色板的信息。 所以 PIL 为您提供调色板索引,而不是该调色板颜色的颜色信息。
编辑:删除了指向有拼写错误的博客文章解决方案的链接。 其他答案在没有错字的情况下做同样的事情。
转换图像的替代方法是从调色板创建 RGB 索引。
from PIL import Image
def chunk(seq, size, groupByList=True):
"""Returns list of lists/tuples broken up by size input"""
func = tuple
if groupByList:
func = list
return [func(seq[i:i + size]) for i in range(0, len(seq), size)]
def getPaletteInRgb(img):
"""
Returns list of RGB tuples found in the image palette
:type img: Image.Image
:rtype: list[tuple]
"""
assert img.mode == 'P', "image should be palette mode"
pal = img.getpalette()
colors = chunk(pal, 3, False)
return colors
# Usage
im = Image.open("image.gif")
pal = getPalletteInRgb(im)
不是 PIL,但imageio.imread
可能仍然很有趣:
import imageio
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
im = imageio.imread('Figure_1.png', pilmode='RGB')
print(im.shape)
给
(480, 640, 3)
所以它是(高度,宽度,通道)。 所以位置(x, y)
处的像素是
color = tuple(im[y][x])
r, g, b = color
scipy.misc.imread
在 SciPy 1.0.0 中被弃用(感谢提醒, fbahr !)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.