How to find the dimensions of an image using Python

In this article, we will discuss how to find the dimensions of an image using Python i.e, the height and width of an image. This is one of the simplest tasks that you might need to do while working with images. The process involved is also just as simple. We will use the Pillow Imaging Library (PIL) of Python.

Installation of Pillow Library for finding dimensions of an image

The task can be solved using OpenCV which is a popular library for working with images in Python but we will make use of a much simpler and lightweight library called Pillow Imaging Library (PIL). To install this, run the following command in your command prompt and it will install everything that’s necessary.

pip install Pillow

To check if the package was correctly installed, run the following code in the Python shell.

import PIL

Make sure the above code doesn’t throw errors before proceeding further.

How to find the dimensions of an image in Python

The code required to do this is extremely simple and consists of just a few lines.

We first need to import the PIL package or specifically the Image class. Then the next step is to create an object of the Image class by referencing the location of the image.

from PIL import Image

# Specify the location of the image
img = Image.open("sample.jpg")

Once we created the Image object, finding the dimensions is as simple as accessing the size member of the object.
It’s a tuple with two elements – the height and the width (in pixels).

The complete code is as follows:

from PIL import Image

# Specify the location of the image
img = Image.open("sample.jpg")

# height and width are in pixels
height, width = img.size


print("Height =", height)
print("Width =", width)

I hope you found the article helpful in finding the height and width of the image using Python. The Pillow library has several other extensive features for handling images. If you want to know more about the Pillow library, you can refer to the official documentation.

See also:

Leave a Reply

Your email address will not be published. Required fields are marked *