有没有办法测量 PNG 图像的内存消耗?
Is there a way to measure the memory consumption of a PNG image?
我想知道 Python 中是否有一种方法可以测量 PNG 图像的内存消耗。
对于我的测试,我需要图像 normal.png
和 evil.png
。假设两张图片的大小均为 100kb。
normal.png
由每个像素 1 个字节表示的数据组成。
evil.png
由 \x00
个字节和一个 PLTE
组成。块 - 每个像素 3 个字节。
对于 normal.png
我可以解压缩 IDAT
数据块,测量大小并将其与原始文件大小进行比较以获得大概的内存消耗。
但是如何进行evil.png
?
您可以使用 Pillow
库来识别图像并获取像素数和 the mode, which can be transformed into the bitdepth:
from PIL import Image
mode_to_bpp = {'1':1, 'L':8, 'P':8, 'RGB':24, 'RGBA':32,
'CMYK':32, 'YCbCr':24, 'I':32, 'F':32}
i = Image.open('warty-final-ubuntu.png')
h, w = i.size
n_pixels = h * w
bpp = mode_to_bpp[data.mode]
n_bytes = n_pixels * bpp / 8
Image.open
还没有载入全部数据;有问题的压缩图像为 3367987 字节,4096000 像素,未压缩时使用 12288000 字节的内存;但是 strace
ing python 脚本显示 Image.open
从内存中的文件中只读取了 4096 字节。
我想知道 Python 中是否有一种方法可以测量 PNG 图像的内存消耗。
对于我的测试,我需要图像 normal.png
和 evil.png
。假设两张图片的大小均为 100kb。
normal.png
由每个像素 1 个字节表示的数据组成。
evil.png
由 \x00
个字节和一个 PLTE
组成。块 - 每个像素 3 个字节。
对于 normal.png
我可以解压缩 IDAT
数据块,测量大小并将其与原始文件大小进行比较以获得大概的内存消耗。
但是如何进行evil.png
?
您可以使用 Pillow
库来识别图像并获取像素数和 the mode, which can be transformed into the bitdepth:
from PIL import Image
mode_to_bpp = {'1':1, 'L':8, 'P':8, 'RGB':24, 'RGBA':32,
'CMYK':32, 'YCbCr':24, 'I':32, 'F':32}
i = Image.open('warty-final-ubuntu.png')
h, w = i.size
n_pixels = h * w
bpp = mode_to_bpp[data.mode]
n_bytes = n_pixels * bpp / 8
Image.open
还没有载入全部数据;有问题的压缩图像为 3367987 字节,4096000 像素,未压缩时使用 12288000 字节的内存;但是 strace
ing python 脚本显示 Image.open
从内存中的文件中只读取了 4096 字节。