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

How do I get a size of a pictures sides with PIL or any other Python library?

This question is related to python python-imaging-library image

The answer is


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 Image
with 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.ndimage
height, width, channels = scipy.ndimage.imread(filepath).shape

Alternative #2: Pygame

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

This is a complete example loading image from URL, creating with PIL, printing the size and resizing...

import requests
h = { 'User-Agent': 'Neo'}
r = requests.get("https://images.freeimages.com/images/large-previews/85c/football-1442407.jpg", headers=h)

from PIL import Image
from io import BytesIO
# create image from binary content
i = Image.open(BytesIO(r.content))


width, height = i.size
print(width, height)
i = i.resize((100,100))
display(i)

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

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

Note that PIL will not apply the EXIF rotation information (at least up to v7.1.1; used in many jpgs). A quick fix to accomodate this:

def get_image_dims(file_path):
    from PIL import Image as pilim
    im = pilim.open(file_path)
    # returns (w,h) after rotation-correction
    return im.size if im._getexif().get(274,0) < 5 else im.size[::-1]

Here's how you get the image size from the given URL in Python 3:

from PIL import Image
import urllib.request
from io import BytesIO

file = BytesIO(urllib.request.urlopen('http://getwallpapers.com/wallpaper/full/b/8/d/32803.jpg').read())
im = Image.open(file)
width, height = im.size

Followings gives dimensions as well as channels:

import numpy as np
from PIL import Image

with Image.open(filepath) as img:
    shape = np.array(img).shape

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to python-imaging-library

How do I install PIL/Pillow for Python 3.6? TypeError: Image data can not convert to float Combine several images horizontally with Python Generate random colors (RGB) How to show PIL Image in ipython notebook Why can't Python import Image from PIL? Importing images from a directory (Python) to list or dictionary ImportError: No module named Image Installing PIL with pip Image.open() cannot identify image file - Python?

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?