In this OpenCV Tutorial, we will learn how to get image size in OpenCV Python using NumPy Array shape property, with an example.
OpenCV Python – Get Image Size
In Image Processing applications, it is often necessary to know the size of an image that is loaded or transformed through various stages.
When working with OpenCV Python, images are stored in numpy ndarray. To get the image shape or size, use ndarray.shape to get the dimensions of the image. Then, you can use index on the dimensions variable to get width, height and number of channels for each pixel.
In the following code snippet, we have read an image to
img ndarray. And then we used ndarray.shape to get the dimensions of the image.
img = cv2.imread('/path/to/image.png') dimensions = img.shape
In this example, we have read an image and used ndarray.shape to get the dimension.
We can access height, width and number of channels from img.shape: Height is at index 0, Width is at index 1; and number of channels at index 2.
import cv2 # read image img = cv2.imread('/home/img/python.png', cv2.IMREAD_UNCHANGED) # get dimensions of image dimensions = img.shape # height, width, number of channels in image height = img.shape width = img.shape channels = img.shape print('Image Dimension : ',dimensions) print('Image Height : ',height) print('Image Width : ',width) print('Number of Channels : ',channels)
Image Dimension : (149, 200, 4) Image Height : 149 Image Width : 200 Number of Channels : 4
img.shape returns (Height, Width, Number of Channels)
- Height represents the number of pixel rows in the image or the number of pixels in each column of the image array.
- Width represents the number of pixel columns in the image or the number of pixels in each row of the image array.
- Number of Channels represents the number of components used to represent each pixel.
In the above example, Number of Channels = 4 represent Alpha, Red, Green and Blue channels.
Concluding this OpenCV Python Tutorial, we have learnt how to get the image shape using OpenCV ndarray.shape.