2012-06-16 46 views
62

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

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

但是,它只輸出一個數(例如01),而不是三個數字(例如60,60,60爲R,G,B)。我想我不瞭解這個功能。我很想解釋一下。

非常感謝。

回答

96

是的,是這樣的:

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貼子:Python and PIL pixel values different for GIF and JPEG和此PIL Reference page包含有關convert()函數的更多信息。

順便說一下,你的代碼對於.jpg圖片來說工作得很好。

+0

可以這樣做的計算機屏幕,而不只是一個圖像文件? – Musixauce3000

+0

是Image.getpixel()基於0還是基於1?我的意思是,最左上角的像素是(0,0)還是(1,1)? – 2017-11-06 02:39:24

+0

@NimaBavari它是基於0的。 – Nolan

2

GIF在調色板中將顏色存儲爲x個可能顏色之一。閱讀關於gif limited color palette。所以PIL給你的調色板索引,而不是該調色板顏色的顏色信息。

編輯:刪除了鏈接到有錯字的博客文章解決方案。其他答案可以在沒有錯字的情況下做同樣的事情。

1

轉換圖像的替代方法是從調色板創建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) 
2

不太平,但仍然scipy.misc.imread可能是有趣:

import scipy.misc 
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB') 
print(im.shape) 

(480, 640, 3) 

所以它是(高度,寬度,信道)。所以在位置(x, y)的像素是

color = tuple(im[y][x]) 
r, g, b = color 
相關問題