In this post, we will learn how to find the size (resolution) of an image using python with detailed explanation and example.

There are two ways to find the size of an image in python.

  1. Using Pillow library
  2. Using OpenCV library

Let’s see both the ways one by one with a simple explanation.

Using Pillow Library

Pillow is a Python external library so we need to install it first. So to install the Pillow library, run below command in the terminal.

pip install pillow

After installing it, run below code to get the size of an Image.

Source Code

from PIL import Image   # from pillow (PIL) import Image

# open your image by specifing path.
img = Image.open("demo.jpg")

# get width and height of an Image using size attribute
width, height = img.size

print(f"Size (Resolution) of your Image is {width} X {height}")

Output

Size (Resolution) of your Image is 1920 X 2531

Using OpenCV Library

As like Pillow, OpenCV is also a Python external library so we need to install it first. So to install the OpenCV library, run below command in the terminal.

pip install opencv-python

After installing the OpenCV library on your system, run the code below to get the size of an image.

Source Code

import cv2  # import open-cv library

# read your image using imread() function
img = cv2.imread("demo.jpg")

# get the size of an image using shape attribute, it return tuple containg three thing height, width & channel 
image_details = img.shape  

print(f"Size (Resolution) of your Image is {image_details[1]} X {image_details[0]}")

Output

Size (Resolution) of your Image is 1920 X 2531

In conclusion, these are the two most common ways to find the size of an image using Python. I hope you found this article helpful. Thank you for reading.

Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment