Python program to find the size of an image

In this article, you will learn how to find the size of an image using two different methods

  1. Using PIL Library
  2. Using OpenCV Library

Finding the size of the image using the PIL Python library

from PIL import Image
import os

img_path = input("Enter the path of the image: ")

if os.path.isfile(img_path):
    with Image.open(img_path) as img:
        width, height = img.size
        print("The size of the image is", width, "x", height)
else:
    print("The path does not exist or is not a file")

In this program, we use the PIL (Python Imaging Library) module to open the image file and get its size.

if you haven’t installed PIL library you can install it by running the command

 pip install Pillow

after that, we provide the path of the image as input from the user and use the Python os module to check if the file exists.

If the file exists, we open the image file using the Image.open() method from PIL and use the size attribute to get the width and height of the image. We then print the size of the image.

Output

C:\Users\user\tutcoach.com>python program.py
Enter the path of the image: C:\Users\user\Desktop\51.jpg
The size of the image is 1996 x 1626

Finding the size of the image using Using OpenCV Library

First, install OpenCV

pip install opencv-python
Python program to find the size of an image python program to find the size of an image,opencv
installing opencv-python in windows 11
import cv2
import os

img_path = input("Enter the path of the image: ")

if os.path.isfile(img_path):
    img = cv2.imread(img_path)
    height, width, channels = img.shape
    print("The size of the image is", width, "x", height)
else:
    print("The path does not exist or is not a file")

In the above program, we use the Python OpenCV library to read the image file and get its size. We take the path of the image as input from the user and use the Python os module to check if the given file exists. If a file exists, we read the file using the cv2.imread() method from OpenCV and use the shape attribute to get the height, width, and number of attributes of the image. We then print the size of the image.

Output

Python program to find the size of an image python program to find the size of an image,opencv
opencv-python output

Conclusion

OpenCV and PIL libraries are incredibly useful tools for working with images in Python. They provide the features like resizing and cropping images for more complex tasks like object detection and image recognition.

The Pillow library is particularly helpful for working with basic image processing tasks in Python, such as resizing, cropping, and rotating images. OpenCV library is more advanced and provides a wide range of image-processing tools for tasks like object detection, facial recognition, and more. It is a powerful library that is widely used in computer vision applications.

Leave a Comment