获取图像大小而不将图像加载到内存中

时间:2013-04-04 00:42:43

标签: python image image-processing

我知道您可以使用PIL以下列方式获取图像大小

from PIL import Image
im = Image.open(image_filename)
width, height = im.size

但是,我想获得图像的宽度和高度,而不必将图像加载到内存中。那可能吗?我只对图像大小进行统计,不关心图像内容。我只想让我的处理更快。

6 个答案:

答案 0 :(得分:73)

如果您不关心图像内容,PIL可能是一种过度杀伤。

我建议解析python magic模块的输出:

>>> t = magic.from_file('teste.png')
>>> t
'PNG image data, 782 x 602, 8-bit/color RGBA, non-interlaced'
>>> re.search('(\d+) x (\d+)', t).groups()
('782', '602')

这是libmagic的包装器,它读取尽可能少的字节以识别文件类型签名。

脚本的相关版本:

https://raw.githubusercontent.com/scardine/image_size/master/get_image_size.py

[更新]

  

嗯,不幸的是,当应用于jpegs时,上面给出了''JPEG图像数据,EXIF标准2.21'“。没有图像尺寸! - 亚历克斯弗林特

似乎jpegs具有抗魔法性。 : - )

我明白为什么:为了获得JPEG文件的图像尺寸,你可能需要阅读比libmagic喜欢阅读更多的字节。

卷起袖子,来了this very untested snippet (get it from GitHub),不需要第三方模块。

Look, Ma! No deps!

#-------------------------------------------------------------------------------
# Name:        get_image_size
# Purpose:     extract image dimensions given a file path using just
#              core modules
#
# Author:      Paulo Scardine (based on code from Emmanuel VAÏSSE)
#
# Created:     26/09/2013
# Copyright:   (c) Paulo Scardine 2013
# Licence:     MIT
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import os
import struct

class UnknownImageFormat(Exception):
    pass

def get_image_size(file_path):
    """
    Return (width, height) for a given img file content - no external
    dependencies except the os and struct modules from core
    """
    size = os.path.getsize(file_path)

    with open(file_path) as input:
        height = -1
        width = -1
        data = input.read(25)

        if (size >= 10) and data[:6] in ('GIF87a', 'GIF89a'):
            # GIFs
            w, h = struct.unpack("<HH", data[6:10])
            width = int(w)
            height = int(h)
        elif ((size >= 24) and data.startswith('\211PNG\r\n\032\n')
              and (data[12:16] == 'IHDR')):
            # PNGs
            w, h = struct.unpack(">LL", data[16:24])
            width = int(w)
            height = int(h)
        elif (size >= 16) and data.startswith('\211PNG\r\n\032\n'):
            # older PNGs?
            w, h = struct.unpack(">LL", data[8:16])
            width = int(w)
            height = int(h)
        elif (size >= 2) and data.startswith('\377\330'):
            # JPEG
            msg = " raised while trying to decode as JPEG."
            input.seek(0)
            input.read(2)
            b = input.read(1)
            try:
                while (b and ord(b) != 0xDA):
                    while (ord(b) != 0xFF): b = input.read(1)
                    while (ord(b) == 0xFF): b = input.read(1)
                    if (ord(b) >= 0xC0 and ord(b) <= 0xC3):
                        input.read(3)
                        h, w = struct.unpack(">HH", input.read(4))
                        break
                    else:
                        input.read(int(struct.unpack(">H", input.read(2))[0])-2)
                    b = input.read(1)
                width = int(w)
                height = int(h)
            except struct.error:
                raise UnknownImageFormat("StructError" + msg)
            except ValueError:
                raise UnknownImageFormat("ValueError" + msg)
            except Exception as e:
                raise UnknownImageFormat(e.__class__.__name__ + msg)
        else:
            raise UnknownImageFormat(
                "Sorry, don't know how to get information from this file."
            )

    return width, height

答案 1 :(得分:51)

正如评论所暗示的那样,PIL在调用.open时不会将图像加载到内存中。查看PIL 1.1.7的文档,.open的文档字符串说:

def open(fp, mode="r"):
    "Open an image file, without loading the raster data"

源中有一些文件操作,如:

 ...
 prefix = fp.read(16)
 ...
 fp.seek(0)
 ...

但这些几乎不构成阅读整个文件。实际上.open只是在成功时返回文件对象和文件名。另外docs说:

  

打开(file,mode =“r”)

     

打开并识别给定的图像文件。

     

这是一个懒惰的操作;此函数标识文件,但在您尝试处理数据(或调用加载方法)之前,不会从文件中读取实际图像数据。

深入挖掘,我们看到.open调用_open这是一种特定于图像格式的重载。可以在新文件中找到_open的每个实现,例如。 .jpeg文件位于JpegImagePlugin.py。让我们深入研究一下。

这里的事情似乎有点棘手,其中有一个无限循环,当找到jpeg标记时会被打破:

    while True:

        s = s + self.fp.read(1)
        i = i16(s)

        if i in MARKER:
            name, description, handler = MARKER[i]
            # print hex(i), name, description
            if handler is not None:
                handler(self, i)
            if i == 0xFFDA: # start of scan
                rawmode = self.mode
                if self.mode == "CMYK":
                    rawmode = "CMYK;I" # assume adobe conventions
                self.tile = [("jpeg", (0,0) + self.size, 0, (rawmode, ""))]
                # self.__offset = self.fp.tell()
                break
            s = self.fp.read(1)
        elif i == 0 or i == 65535:
            # padded marker or junk; move on
            s = "\xff"
        else:
            raise SyntaxError("no marker found")

如果格式错误,可以读取整个文件。如果它读取信息标记OK,它应该提前爆发。函数handler最终设置self.size,它们是图像的维度。

答案 2 :(得分:5)

我经常在互联网上获取图片大小。当然,您无法下载图像,然后加载它来解析信息。这太费时间了。我的方法是将块提供给图像容器并测试它是否可以每次解析图像。当我得到我想要的信息时停止循环。

我解压缩了代码的核心并对其进行了修改以解析本地文件。

from PIL import ImageFile

ImPar=ImageFile.Parser()
with open(r"D:\testpic\test.jpg", "rb") as f:
    ImPar=ImageFile.Parser()
    chunk = f.read(2048)
    count=2048
    while chunk != "":
        ImPar.feed(chunk)
        if ImPar.image:
            break
        chunk = f.read(2048)
        count+=2048
    print(ImPar.image.size)
    print(count)

输出:

(2240, 1488)
38912

实际文件大小为1,543,580字节,您只能读取38,912字节来获取图像大小。希望这会有所帮助。

答案 3 :(得分:4)

在pypi上有一个名为imagesize的程序包目前对我有用,尽管它看起来不太活跃。

安装:

pip install imagesize

用法:

import imagesize

width, height = imagesize.get("test.png")
print(width, height)

主页:https://github.com/shibukawa/imagesize_py

PyPi:https://pypi.org/project/imagesize/

答案 4 :(得分:1)

在Unix系统上执行此操作的另一种简短方法。它取决于file的输出,我不确定它是否在所有系统上都是标准化的。这可能不应该在生产代码中使用。此外,大多数JPEG不报告图像大小。

import subprocess, re
image_size = list(map(int, re.findall('(\d+)x(\d+)', subprocess.getoutput("file " + filename))[-1]))

答案 5 :(得分:0)

answer具有另一个良好的分辨率,但缺少 pgm 格式。此answer已解决 pgm 。我添加 bmp

代码在下面

import struct, imghdr, re, magic

def get_image_size(fname):
    '''Determine the image type of fhandle and return its size.
    from draco'''
    with open(fname, 'rb') as fhandle:
        head = fhandle.read(32)
        if len(head) != 32:
            return
        if imghdr.what(fname) == 'png':
            check = struct.unpack('>i', head[4:8])[0]
            if check != 0x0d0a1a0a:
                return
            width, height = struct.unpack('>ii', head[16:24])
        elif imghdr.what(fname) == 'gif':
            width, height = struct.unpack('<HH', head[6:10])
        elif imghdr.what(fname) == 'jpeg':
            try:
                fhandle.seek(0) # Read 0xff next
                size = 2
                ftype = 0
                while not 0xc0 <= ftype <= 0xcf:
                    fhandle.seek(size, 1)
                    byte = fhandle.read(1)
                    while ord(byte) == 0xff:
                        byte = fhandle.read(1)
                    ftype = ord(byte)
                    size = struct.unpack('>H', fhandle.read(2))[0] - 2
                # We are at a SOFn block
                fhandle.seek(1, 1)  # Skip `precision' byte.
                height, width = struct.unpack('>HH', fhandle.read(4))
            except Exception: #IGNORE:W0703
                return
        elif imghdr.what(fname) == 'pgm':
            header, width, height, maxval = re.search(
                b"(^P5\s(?:\s*#.*[\r\n])*"
                b"(\d+)\s(?:\s*#.*[\r\n])*"
                b"(\d+)\s(?:\s*#.*[\r\n])*"
                b"(\d+)\s(?:\s*#.*[\r\n]\s)*)", head).groups()
            width = int(width)
            height = int(height)
        elif imghdr.what(fname) == 'bmp':
            _, width, height, depth = re.search(
                b"((\d+)\sx\s"
                b"(\d+)\sx\s"
                b"(\d+))", str).groups()
            width = int(width)
            height = int(height)
        else:
            return
        return width, height
相关问题