cv2.imread() method Python OpenCV (original) (raw)
Last Updated : 14 Apr, 2025
**OpenCV-Python is a Python library used to solve computer vision tasks. **cv2.imread() method loads an image from the specified file. If the image cannot be read because of missing file, improper permissions or an unsupported/invalid format then it returns an empty matrix.
**Example:
Python `
import cv2
image = cv2.imread("image.png")
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
`
**Output:
Example Image
**Syntax of cv2.imread() Method
cv2.imread(filename, flag)
**Parameters:
- **filename: specifies **the path to the image file.
- **flag: specifies the way how the image should be read which can be :
- **cv2.IMREAD_COLOR – It specifies to load a color image. Any transparency of image will be neglected. It is the default flag. Alternatively we can pass integer value **1 for this flag.
- **cv2.IMREAD_GRAYSCALE – It specifies to load an image in grayscale mode. Alternatively we can pass integer value **0 for this flag.
- **cv2.IMREAD_UNCHANGED – It specifies to load an image such as including alpha channel. Alternatively we can pass integer value **-1 for this flag.
The **cv2.imread() function return a NumPy array if the image is loaded successfully.
Examples of OpenCV cv2.imread() Method
Below is the sample image we will be using:
Input Image
1. Using cv2 imread() function to read a colored image:
In this example we are reading the image as a color image. We will use **cv.imread() function to take the image as an input and **cv.imshow() function to display the image.
Python `
import cv2 image = cv2.imread("gfg.jpeg")
cv2.imshow("Image", image)
cv2.waitKey(0) cv2.destroyAllWindows()
`
**Output:
Colored image
Here we can see that by default our image got read and displayed in coloured image.
2. Reading image in grayscale
In this example we are reading the image as a greyscale image. Both color and grayscale images are acceptable as input.
Python `
import cv2
image = cv2.imread("gfg.jpeg",cv2.IMREAD_GRAYSCALE)
cv2.imshow("Image", image)
cv2.waitKey(0) cv2.destroyAllWindows()
`
**Output:
Grayscale Image
3. Reading PNG Image with Transparency
In this example we are reading the image with the transparency channel i.e the alpha channel. It represents the transparency or opacity of an image. It controls how transparent or solid each pixel is with value of 0 indicating full transparency and 255 representing full opacity.
Python `
import cv2 image = cv2.imread("gfg.jpeg",cv2.IMREAD_UNCHANGED)
cv2.imshow("Image", image)
cv2.waitKey(0) cv2.destroyAllWindows()
`
**Output:
Image with Aplha Channel
cv2.imread()
method is a fundamental function for reading image files. It loads images into memory allowing us image manipulation and analysis. By specifying the appropriate flag you can control how the image is loaded and used for analysis.