tags:

views:

71

answers:

4

I have a list (the paths) of images saved locally. How can I find the largest image from these? I'm not referring to the file size but the dimensions.

All the images are in common web-compatible formats — JPG, GIF, PNG, etc.

Thank you.

A: 
import Image

src = Image.open(image)
size = src.size 

size will be a tuple with the image dimensions (witdh and height)

munissor
+1  A: 

You will need PIL.

from PIL import Image

img = Image.open(image_file)
width, height = img.size

Once you have the size of a single image, checking the whole list and selecting the bigger one is not the problem.

Maciej Kucharz
+3  A: 

Use Python Imaging Library (PIL). Something like this:

from PIL import Image
filenames = ['/home/you/Desktop/chstamp.jpg', '/home/you/Desktop/something.jpg']
sizes = [Image.open(f, 'r').size for f in filenames]
max(sizes)

Update (Thanks delnan):

Replace last two lines of above snippet with:

max(Image.open(f, 'r').size for f in filenames)

Update 2

The OP wants to find the index of the file corresponding to the largest dimensions. This requires some help from numpy. See below:

from numpy import array
image_array = array([Image.open(f, 'r').size for f in filenames])
print image_array.argmax()
Manoj Govindan
That should really be `max(Image.open(f, 'r').size for f in filenames)` (generator expression!).
delnan
Thanks Manoj. I like the method of yours using lambda functions. In this exmaple, can i also get the index/location of the image that was the largest?I could always write a `for` loop to iterate over the whole thing but my method isn't as clean and concise as yours.
Mridang Agarwalla
@Mridang: Eh, lambda? Don't you mean list comprehension?
delnan
@delnan: Thanks. Changing it.
Manoj Govindan
@Mridang: Updated my answer to find index of largest image. See above.
Manoj Govindan
@Mridang: Delnan is correct; I used list comprehension and not lambda.
Manoj Govindan
@delnan/@Manoj: My bad. That's what i meant. Thanks for the help.
Mridang Agarwalla
I like your solution but it means using an additonal library. Would it considered kludy if i tried to get the index by this using `largest = max(sizes)`. `sizes.index(largest)`. This would give us the index in the sizes array which has the largest value. Since the second array is built by iterating over the first array, the indices would be in sync and the index of the largest value in the second array would correspond to the index of the image in the first. What's your take on this? I'm not handling scenarions where more than image has the same dimensions.
Mridang Agarwalla
@Mridang: sounds good to me :)
Manoj Govindan
+4  A: 

Assuming that the "size" of an image is its area :

from PIL import Image

def get_img_size(path):
    width, height = Image.open(path).size
    return width*height

largest = max(the_paths, key=get_img_size)
dugres