How to Use the OpenCV imread Function in Python



In this article, you will learn how to use the OpenCV imread function in Python.

OpenCV imread Function

OpenCV is a popular open-source computer vision library that provides many useful image processing functions. The imread function is one of the most frequently used functions in OpenCV that loads an image from a file into a NumPy array. Here are the steps to use the imread function in Python:

Install OpenCV

You need to install OpenCV in your Python environment. You can install it using pip. In your terminal or command prompt, type:

pip install opencv-python
Import OpenCV

After installation, import the OpenCV library in your Python script:

import cv2
Load an Image

Use the imread function to load an image from a file. You need to pass the image file path as an argument to the imread function:

image = cv2.imread('image_path.jpg')

Here, ‘image_path.jpg’ is the path to the image file that you want to load. The imread function returns a NumPy array that contains the pixel values of the image.

Display the Image

To display the loaded image, use the imshow function from OpenCV. Here’s an example:

cv2.imshow('Image', image)

The imshow function displays the image in a window with the given name (‘Image’ in this case). The waitKey function waits for a keyboard event for a specified amount of time (here, 0 means to wait indefinitely). The destroyAllWindows function closes all the windows.