How do I get the picture size with PIL? How do I get the picture size with PIL? python python

How do I get the picture size with PIL?


from PIL import Imageim = Image.open('whatever.png')width, height = im.size

According to the documentation.


You can use Pillow (Website, Documentation, GitHub, PyPI). Pillow has the same interface as PIL, but works with Python 3.

Installation

$ pip install Pillow

If you don't have administrator rights (sudo on Debian), you can use

$ pip install --user Pillow

Other notes regarding the installation are here.

Code

from PIL import Imagewith Image.open(filepath) as img:    width, height = img.size

Speed

This needed 3.21 seconds for 30336 images (JPGs from 31x21 to 424x428, training data from National Data Science Bowl on Kaggle)

This is probably the most important reason to use Pillow instead of something self-written. And you should use Pillow instead of PIL (python-imaging), because it works with Python 3.

Alternative #1: Numpy (deprecated)

I keep scipy.ndimage.imread as the information is still out there, but keep in mind:

imread is deprecated! imread is deprecated in SciPy 1.0.0, and [was] removed in 1.2.0.

import scipy.ndimageheight, width, channels = scipy.ndimage.imread(filepath).shape

Alternative #2: Pygame

import pygameimg = pygame.image.load(filepath)width = img.get_width()height = img.get_height()


Since scipy's imread is deprecated, use imageio.imread.

  1. Install - pip install imageio
  2. Use height, width, channels = imageio.imread(filepath).shape