7

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.

1
  • In the case of JPEG it is not trivial, since the image attributes are not stored in a plain, reader-friendly format. Instead, JPEG data is stored as a concatenation of segments. I found this answer quite interesting: (stackoverflow.com/a/18264693/2863154) Commented May 20, 2014 at 16:08

1 Answer 1

15

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().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.