Python OpenCV: Getting image dimensions

In this tutorial we will learn how to obtain the dimensions (height and width) of an image read with OpenCV, using Python.

Introduction

In this tutorial we will learn how to obtain the dimensions (height and width) of an image read with OpenCV, using Python.

This tutorial was tested with version 4.0.0 of OpenCV and version 3.7.2 of Python.

The code

We will start the code by importing the cv2 module, so we have access to the OpenCV functionalities.

import cv2

Followed by that we will read an image with the imread function of the cv2 module. As input, we simply need to pass the path to the image.

image = cv2.imread('C:/Users/N/Desktop/testImg.png')

We are going to be reading the following test image:

Testing image
Figure 1 – Testing image used.

As can be seen in figure 2, the image has a width of 701 pixels and a height of 568 pixels.

Dimensions of the image.
Figure 2 – Dimensions of the image.

Note that when we read an image with the imread function, we get a ndarray representing our image. Thus, we can use the shape attribute to obtain the dimensions of the ndarray.

This attribute is a tuple that contains, by this order, the height, the width and the number of channels of the image. We will access this attribute print it.

print(image.shape)

The final code can be seen below.

import cv2

image = cv2.imread('C:/Users/N/Desktop/testImg.png')

print(image.shape)

Testing the code

To test the code, simply run it in a tool of your choice. In my case I’m using IDLE.

You should get an output similar to figure 3. As can be seen, I’ve obtained a tuple which indicates that my image has a height of 568 pixels and a width of 701 pixels, like expected. Additionally, it is possible to see that the image I’ve used has 3 channels.

Figure 3 – Result of the program, showing the dimensions and the number of channels of the image.

Leave a Reply

%d bloggers like this: