【问题标题】:How can I read how many pixels an image has in Python [duplicate]如何在 Python 中读取图像有多少像素 [重复]
【发布时间】:2010-12-07 05:34:55
【问题描述】:

可能重复:
How to check dimensions of all images in a directory using python?

我想知道是否有人知道如何在 python sript 中读取图像总像素数。你能提供和例子吗?

非常感谢。

【问题讨论】:

标签: python pixels


【解决方案1】:

这是一个例子:

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 我插入了位于我的项目目录中的文件的文件名,但我仍然收到unresolved file reference 错误。
【解决方案2】:

使用PIL 加载图像。像素总数将是它的宽度乘以它的高度。

【讨论】:

    【解决方案3】:

    这是您要求的示例:

    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
    

    【讨论】:

    • 如果我想在 R、G 和 B 中分割总像素怎么办?????
    • @M.D.P:乘以 3?我不确定你的意思。每个像素都有一个用于 R、G 和 B 的组件。
    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 2018-03-14
      相关资源
      最近更新 更多