Introduction
OpenCV stands for Open Source Computer Vision Library. It is a practical open-source toolkit created to help programmers and academics create programs that analyze photos and videos, from straightforward operations like reading and displaying images to complex ones like object detection and facial recognition.
In this blog, we will discuss the OpenCV cv2.imread() function in Python. Let’s start going!
cv2.imread() in OpenCV
The OpenCV cv2.imread() function is used to read an image file from the given directory and return a NumPy array containing the pixel values for the picture. The OpenCV library's other functions and resources can process, analyze, or edit this NumPy array.
Syntax
The basic syntax of cv2.imread() is:-
import cv2
image = cv2.imread(filename, flag)
Parameter
The parameter of cv2.imread() are:-
-
filename: The path to the image file you want to load is specified by this option. The path to your filesystem's image file can be absolute or relative.
-
flags: The flags argument is an optional parameter that specifies how the picture should be loaded and read. It establishes the loaded image's color space and channel settings. It is an integer with a range of specified constants that it can accept. Some basic flags include are:-
-
cv2.IMREAD_COLOR: This default flag loads the image in the BGR color format. It is the same as passing the value of the flag as 1.
-
cv2.IMREAD_GRAYSCALE: This flag loads the image in grayscale. It is the same as supplying the value 0 for the flag.
- cv2.IMREAD_UNCHANGED: If an alpha channel is present, the image is loaded exactly as it is with this flag set. It is the same as setting the flag value to -1.
-
cv2.IMREAD_COLOR: This default flag loads the image in the BGR color format. It is the same as passing the value of the flag as 1.
Return Value
An OpenCV cv2.imread() method returns a NumPy array representing the loaded picture. Some important points regarding return value are:-
-
If we use the cv2.IMREAD_COLOR flag, the function will return a 3D NumPy array that represents a color image. The array will have the following dimensions: height, breadth, and channels.
-
If the cv2.IMREAD_GRAYSCALE parameter is used, and a 2D NumPy array depicting a grayscale image will be returned. The array's dimensions are (height, width).
- If the cv2.IMREAD_UNCHANGED flag is used; the function will return a 3D NumPy array with the original image's color channels and any alpha channels that may have been present. The array will have the following dimensions: height, breadth, and channels.