gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:09:15 25 4
gpt4 key购买 nike

我了解您可以通过以下方式使用 PIL 获取图像大小

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

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

最佳答案

如果你不关心图像内容,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

[更新]

Hmmm, unfortunately, when applied to jpegs, the above gives "'JPEG image data, EXIF standard 2.21'". No image size! – Alex Flint

似乎 jpeg 具有抗魔力。 :-)

我明白为什么:为了获得 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

[2019 年更新]

查看一个 Rust 实现:https://github.com/scardine/imsz

关于python - 获取图像大小而不将图像加载到内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15800704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com