Is there a way to examine how much memory an image

2019-07-23 16:03发布

pillow provides size to examine the resolution of an image.

>> from PIL import Image
>> img = Image.open('Lenna.png')
>> img.size
(512, 512)

is there a way to examine how many memory the image is occupying? is the image using 512*512*4 Bytes memory?

2条回答
\"骚年 ilove
2楼-- · 2019-07-23 16:33

You could use the sys library to get the size of an object in bytes. The difference with Kai's answer is that he's calculating the size of the image on the disk, while this calculates the size of the loaded python object (with all its metadata):

import sys

sys.getsizeof(img)

EDIT: After seeing this website, sys.getsizeof() seems to work mainly for primitive types.

You could have a look at a more thorough implementation (deep_getsizeof()) here .

This post gives also a lot of details.

And finally, there is also the pympler library that provides tools to calculate the RAM memory used by an object.

from pympler import asizeof

asizeof.asizeof(img)
查看更多
小情绪 Triste *
3楼-- · 2019-07-23 16:55
import os
print os.stat('somefile.ext').st_size

or

import os
os.path.getsize('path_to_file.jpg')`
查看更多
登录 后发表回答