In this article, we are going to discuss how to get the height and width of a particular image.
In order to find the height and width of an image, there are two approaches. The first approach is by using the PIL(Pillow) library and the second approach is by using the Open-CV library.
PIL is the Python Imaging Library is an important module which is used for image processing. It supports many formats of images such as “jpeg”, “png”, “ppm”, “tiff”, “bmp”, “gif”. It provides many image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image.
PIL.Image.open() is used to open the image and then .width and .height property of Image are used to get the height and width of the image. The same results can be obtained by using .size property.
To use pillow library run the following command:
pip install pillow
An alternate way to get height and width is using .size property.
OpenCV in python is a library which is used for computer vision, image processing and much more. The imread(filepath) function is used to load an image from the file path specified. The .shape stores a tuple of height, width and no of channels for each pixel. The .shape[:2] will get the height and width of the image.
To install OpenCV run the following command:
pip install opencv-python
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.