We all must have moved our mouse cursors to an image file and within a fraction of a second a small box appears displaying the dimensions of the image. How easy is that! But can we get the size of an image using programming and coding?
Well, yes we can get the size of the image using Programing and that’s where Python Programing Language comes into play.
Since Python is extensively used for real-life applications such as Web-Development, Machine Learning, Artificial Intelligence, Data Science, etc and it’s of no surprise that we can get the size (dimensions) of any image using Python OpenCV.
We are going to learn about how to fetch the size of the image using OpenCV Python with an example. Let’s get started.
Also read: Image Processing in Python – Edge Detection, Resizing, Erosion, and Dilation
During image processing, it’s essential to know the size of the image with which we work, which is being transformed through various stages.
An Image is a 2-D array of Pixels. Dimensions of the image refer to the height, width, and number of channels of the image. When working with OpenCV, images are stored in NumPy ndarray(N-Dimensional array).
Pre – Requisites
- The latest version of Python must be installed on your respective systems, it can be installed from https://www.python.org/downloads/
- Install OpenCV by executing the following command in your terminal:
pip install opencv-contrib-python
Reading the Image
The image can be loaded using imread function of OpenCV.
# Importing the OpenCV Module import cv2 as cv # Reading the image using imread() function img = cv.imread('IMAGES/Puppy.jpg')
In the above snippet,
imread function takes the path to the image as an argument.
Example – Get the Image Size Using OpenCV
In this example, I have used the following image, and the dimensions of the image are 406×503 where the Width is 406px and the Height is 503px.
In order to get the size of the image
ndarray.shape is used where
ndarray is the image read using
imread function. The
shape returns a tuple that has 3 values – height, width, and the number of channels. Height is at index 0, Width is at index 1, and Number of channels is at index 2.
# Importing the OpenCV Module import cv2 as cv # Reading the image using imread() function img = cv.imread('IMAGES/Puppy.jpg') dimensions = img.shape #Accessing height, width and channels # Height of the image height = img.shape # Width of the image width = img.shape # Number of Channels in the Image channels = img.shape # Displaying the dimensions of the Image print("Dimension are :",dimensions) print("Height :",height,"px") print("Width :",width,"px") print("Number of Channels : ",channels)
Dimension are : (503, 406, 3) Height : 503 px Width : 406 px Number of Channels : 3
That’s really interesting our code produced the exact dimensions of the image.
That was about fetching the size(dimensions) of the image using OpenCV. Make sure you give the full path of the image to be read. Thanks for reading and Happy Coding!