How to Read Image Using OpenCV in Python - Simple Guide
Use
cv2.imread() to read an image file in Python with OpenCV. Provide the image path as a string argument, and it returns the image as a NumPy array.Syntax
The basic syntax to read an image using OpenCV in Python is:
cv2.imread(filename, flags)
Where:
filenameis the path to the image file as a string.flagsis optional and defines how the image is read (color, grayscale, etc.).
python
import cv2 image = cv2.imread('path/to/image.jpg', cv2.IMREAD_COLOR)
Example
This example reads an image file named example.jpg in color mode and prints its shape (dimensions).
python
import cv2 # Read the image in color mode image = cv2.imread('example.jpg', cv2.IMREAD_COLOR) # Check if image was loaded successfully if image is not None: print('Image shape:', image.shape) else: print('Failed to load image')
Output
Image shape: (height, width, 3)
Common Pitfalls
Common mistakes when reading images with OpenCV include:
- Using a wrong or non-existent file path, which causes
cv2.imread()to returnNone. - Not checking if the image was loaded before using it, leading to errors.
- Confusing color channels because OpenCV reads images in BGR order, not RGB.
python
import cv2 # Wrong way: not checking if image loaded image = cv2.imread('wrong_path.jpg') print(image.shape) # This will cause an error if image is None # Right way: check before using image = cv2.imread('correct_path.jpg') if image is not None: print(image.shape) else: print('Image not found')
Output
Image not found
Quick Reference
| Parameter | Description | Common Values |
|---|---|---|
| filename | Path to the image file | 'image.jpg', 'folder/pic.png' |
| flags | How to read the image | cv2.IMREAD_COLOR (default), cv2.IMREAD_GRAYSCALE, cv2.IMREAD_UNCHANGED |
Key Takeaways
Use cv2.imread() with the image file path to read images in OpenCV.
Always check if the image loaded successfully before processing it.
The default color mode reads images in BGR format, not RGB.
Provide the correct file path to avoid getting None as the result.
Use flags to control how the image is read (color, grayscale, etc.).