簡體   English   中英

使用 PIL 獲取像素的 RGB

[英]Get pixel's RGB using PIL

是否可以使用 PIL 獲取像素的 RGB 顏色? 我正在使用這段代碼:

im = Image.open("image.gif")
pix = im.load()
print(pix[1,1])

但是,它只輸出一個數字(例如01 )而不是三個數字(例如 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM