How to access image properties in OpenCV using Python?


An image in OpenCV is a NumPy array. We can access the image properties using the attributes of the numpy array. We access the following image properties for the input image img

  • Image Type − data structure of the mage. Image in OpenCV is numpy.ndarray. We can access it as type(img).

  • Image Shape − It is the shape in [H, W, C] format, where H, W, and C are the height, width and number of channels of the image respectively. We can access it as img.shape.

  • Image Size − It is the total number of pixels in an image. Also it is the total number of elements in the array. We can access it as img.size.

  • Data type − its the dtype of elements of the image array. We can access it as img.dtype.

  • Dimension − the dimension of image. A color image has 3 dimensions (height, width and channels) whereas a gray image has 2 dimensions (only height and width). We can access it as img.ndim.

  • Pixel values − the pixel values are unsigned integers in range 0 and 255. We can directly access these values as print(img).

Let's have a look at some Python programs to access the properties of an image.

Input Image

We will use this image as the input file in the following examples.

Example 1

In this program, we will access the image properties of the given color image.

import cv2 # read the input image img = cv2.imread('cat.jpg') # image properties print("Type:",type(img)) print("Shape of Image:", img.shape) print('Total Number of pixels:', img.size) print("Image data type:", img.dtype) # print("Pixel Values:\n", img) print("Dimension:", img.ndim)

Output

When you run this program, it will produce the following output −

Type: <class 'numpy.ndarray'=""> 
Shape of Image: (700, 700, 3) 
Total Number of pixels: 1470000 
Image data type: uint8 
Dimension: 3

Let’s look at another example.

Example 2

In this program, we will access the image properties of a gray mage.

import cv2 # read the input image img = cv2.imread('cat.jpg', 0) # image properties print("Type:",type(img)) print("Shape of Image:", img.shape) print('Total Number of pixels:', img.size) print("Image data type:", img.dtype) print("Pixel Values:\n", img) print("Dimension:", img.ndim)

Output

When you run the above python program, it will produce the following output −

Type: <class 'numpy.ndarray'> 
Shape of Image: (700, 700) 
Total Number of pixels: 490000 
Image data type: uint8 
Pixel Values:
   [[ 92 92 92 ... 90 90 90]
   [ 92 92 92 ... 90 90 90] 
   [ 92 92 92 ... 90 90 90] 
   ... 
   [125 125 125 ... 122 122 121] 
   [126 126 126 ... 122 122 122] 
   [126 126 126 ... 123 123 122]] 
Dimension: 2

Updated on: 27-Sep-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements