Tuesday, 7 November 2023

How to Read an Image with OpenCV?

In this post, I am going to walk you through on ‘how to read and display an image’ using opencv library.

Step 1: Import opencv library.

import cv2 as cv

‘cv’ is an alias name given the cv2 module. This alias is used to reference the OpenCV functions and classes throughout the code

 

Step 2: Read the image file.

image_data = cv.imread('photos/tiger.png')

'imread' method takes the file name or path of the image and returns the image data as a NumPy array. This array represents the pixel values of the image.

 

Step 3: Display the image.

cv.imshow('Tiger', image_data)

'imshow' method displays the image in a new window. First argument 'Tiger' specifies the title of the window in which the image is displayed. Second argument ‘image_data’ specifies the data that you want to display.

 

Step 4: Wait for a keyboard event to occur to close the image.

cv.waitKey(0)

'waitKey' function is used to wait for a keyboard event to occur. As I passed the argument as 0 this function, it waits indefinitely until a key is pressed.

 

Step 5: Close all the currently open windows.

cv.destroyAllWindows()

When you want to close all OpenCV windows and exit your application gracefully,  use destroyAllWindows method. Calling ‘destroyAllWindows’ method prevent resource leakage issues.

 

Find the below working application.

 

read_image.py

import cv2 as cv

# Read the image as matrix of pixels
image_data = cv.imread('photos/tiger.png')
print(f'type of image_data  is {type(image_data)}')

# Display the image in new window
cv.imshow('Tiger', image_data)

# Wait for Infinite amount of time for a keyboard key to be pressed
cv.waitKey(0)

# Close the OpenCV windows
cv.destroyAllWindows()

Output



How to close the Application?

Move the mouse pointer over the image and click any key.


Previous                                                    Next                                                    Home

No comments:

Post a Comment