画像をメモリにロードせずに画像サイズを取得する 質問する

画像をメモリにロードせずに画像サイズを取得する 質問する

PILを使用して画像サイズを次のように取得できると理解しています

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

しかし、画像の幅と高さを取得したいのですがそれなし画像をメモリにロードする必要があります。それは可能ですか? 画像サイズの統計のみを行っており、画像の内容は気にしていません。処理を高速化したいだけです。

ベストアンサー1

画像の内容にこだわらない場合は、PIL はおそらくやりすぎです。

Python マジック モジュールの出力を解析することをお勧めします。

>>> 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

[アップデート]

うーん、残念ながら、JPEG に適用すると、上記は「JPEG 画像データ、EXIF 標準 2.21」になります。画像サイズがありません! – Alex Flint

jpeg は魔法耐性があるようです。:-)

理由はわかります。JPEG ファイルの画像サイズを取得するには、libmagic が読み取るバイト数よりも多くのバイト数を読み取る必要がある可能性があります。

袖をまくってこれはまったくテストされていないスニペットです (GitHub から取得)サードパーティのモジュールを必要としません。

見てよママ!デップスなしよ!

#-------------------------------------------------------------------------------
# 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

[2019年更新]

Rust の実装を確認してください:https://github.com/scardine/imsz

おすすめ記事