OpenCV with Python for Beginners : Day 2

Shape, Size, and Data type of an image

Understanding the size, data type, and shape of an image is crucial in OpenCV for several reasons: it enables accurate image manipulation, avoids errors during processing, and ensures compatibility with different functions and algorithms. Knowing these properties helps in tasks like resizing, format conversions, and ensuring correct data handling. 

In this example we will learn how to get these information by the method cv2.imread()

Step 1 : On a new python file add the code lines

import cv2
img_path = 'img/r0_0.jpg'
img_original = cv2.imread(img_path)

the same as the previous example, just to reminding, the first line import the cv2 library, then the variable store the path of the image to load and finally the variable img_orginal load the image.

Step 2 : Use the command print to display on the screen the labels and value for the data retrieved from image, first will see how to print the labels, add the lines below:

print('data type:')
print('image shape:')
print('image size:')

save the file and run the code , should get this result

Step 3: Now use the attribute dtype to retrieve the data type, OpenCV uses BGR (instead of scikit-image’s RGB) for color images, and its dtype is uint8 by default.

print('data type:', img_original.dtype)

Save the file and run the code, should get this result

Step 4: Use the attribute shape to retrieve the shape of the image,  It returns a tuple of the number of rows, columns, and channels (342, 548, 3), an image from a standard digital camera will have a red, green and blue channel. A grayscale image has just one channel.

print('image shape:', img_original.shape)

Save the file and run the code, should get this result

Step 5: Finally use the attribute size to retrieve the total number of pixels, knowing the total number of pixels in an image, often referred to as its resolution, is important because it directly impacts the image’s quality, file size, and how it can be used.

print('image size:', img_original.size)

Save the file and run the code, should get this result

Comments are closed