如何在Python中读取图像的像素数

如何在Python中读取图像的像素数,python,pixels,Python,Pixels,可能重复: 我想知道是否有人知道如何在python sript中读取图像的像素总量。你能举个例子吗 非常感谢。用于加载图像。像素总数将是其宽度乘以其高度。PIL,Python图像库可以帮助您从图像的元数据中获取此信息。以下是您要求的示例: from PIL import Image import os.path filename = os.path.join('path', 'to', 'image', 'file') img = Image.open(filename) width, he

可能重复:

我想知道是否有人知道如何在python sript中读取图像的像素总量。你能举个例子吗


非常感谢。

用于加载图像。像素总数将是其宽度乘以其高度。

PIL,Python图像库可以帮助您从图像的元数据中获取此信息。

以下是您要求的示例:

from PIL import Image
import os.path

filename = os.path.join('path', 'to', 'image', 'file')
img = Image.open(filename)
width, height = img.size
print "Dimensions:", img.size, "Total pixels:", width * height
以下是一个例子:

from PIL import Image

def get_num_pixels(filepath):
    width, height = Image.open(filepath).size
    return width*height

print get_num_pixels("/path/to/my/file.jpg")

使用复制如果这是一个复制品,它比原来的要有用得多。虽然没有错误,
open(filepath)
不是必需的-
Image.open()
只接受文件名。@mhawke我插入了项目目录中的文件名,但是我仍然得到
未解析的文件引用
错误。如果我要将R、G和B中的总像素拆分,该怎么办?@M.D.P:乘以3?我不知道你的意思。每个像素都有一个R、G和B的分量。