Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting the shape of an image file from python without loading the image

Is there an efficient way to know the size (height, weight, channels) of an image file, without actually loading it into python?

The trivial way would be:

img = cv2.imread('a.jpg')
print img.shape

but that would waste the CPU (and memory) as I don't need the image itself.

like image 212
eran Avatar asked Dec 14 '22 22:12

eran


1 Answers

PIL's Image.open doesn't load the image data until it needs to, as seen in the docs,

This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the load() method). See new().

To check this in ipython I ran

im = Image.open(filename)
im.size

on a 22MB image, ps -av reported:

33714 17772  0.8 /usr/bin/python2 /usr/bin/ipython2
34506 18220  0.8 /usr/bin/python2 /usr/bin/ipython2
34506 18220  0.8 /usr/bin/python2 /usr/bin/ipython2

for memory usage, before open, before size and after size, confirming that the 22MB image hasn't been loaded into memory (ipython started out using 32538 17252).
That figure then jumps up to ~57k following im.load().

like image 170
jmetz Avatar answered Dec 17 '22 12:12

jmetz