使用PIL分析像素RGB值

时间:2015-11-04 20:56:43

标签: python

我正在开发一个项目,我需要找到图片中每个像素的RGB值。我怎么能用PIL做到这一点?我知道Pillow更好,但因为我只需要做一件事我认为我可以使用PIL。如果这不起作用,请告诉我。

3 个答案:

答案 0 :(得分:0)

from PIL import Image
img = Image.open("filename.png")
pixels = img.load()

#get the B value of the pixel at x=23, y=42
print pixels[23, 42][2]

答案 1 :(得分:0)

之前的答案是一个很好的解决方案,但只是建议另一种方式是一行:

from scipy import misc;

imgData = misc.imread('./image.png');

然后,您可以轻松获得所需的每个像素的颜色。

答案 2 :(得分:0)

Kevin非常注重,您也可以使用getdata()返回元组列表。

我可能完全错了,但如果您需要特定的像素,load()可能效果更好,如果您需要所有像素,getdata()可能会更好。image = Image.open('filename').convert('RGB') width, height = image.size #Get pixels in a list of tuples pixels = image_input.getdata() #If you need a flat list containing all the colours bytes = [j for i in pixels for j in i] 另外,如果它只是一个普通的图像,转换为RGB是一个好主意,之前我没有做过错误。

for key, value in dictionary.items():
    # Do something with the key or the value here.

如果您需要对像素进行处理并重建图像,那么图像大小就会变得有用。