Reading an image is the first practical step in every computer vision and image processing project. Before applying filters, detecting faces, recognizing objects, or performing image transformations, you must first load the image into your Python program. OpenCV provides a simple yet powerful function called cv2.imread() that allows you to read images from your computer and store them as NumPy arrays.
In this lesson, you will learn how to read images using OpenCV, understand different image reading modes, verify whether an image has been loaded successfully, and explore how OpenCV internally stores image data.
The cv2.imread() function is used to load an image from a file. It reads the image stored on your computer and converts it into a NumPy array that can be processed using OpenCV functions.
Syntax:
cv2.imread(filename, flags)
Parameters:
Return Value:
If the image is loaded successfully, OpenCV returns a NumPy array. If the file cannot be found or opened, it returns None.
The simplest way to load an image is by providing its filename.
import cv2
image = cv2.imread("sample.jpg")
If sample.jpg exists in the current working directory, OpenCV will load it successfully.
Always verify that the image has been loaded before performing any operations. Attempting to process a missing image will result in errors.
import cv2
image = cv2.imread("sample.jpg")
if image is None:
print("Error: Image not found.")
else:
print("Image loaded successfully.")
Checking for None is considered a best practice in every OpenCV program.
OpenCV can read images using either relative paths or absolute paths.
image = cv2.imread("images/sample.jpg")
The file is searched relative to the current project folder.
image = cv2.imread("C:/Users/Student/Pictures/sample.jpg")
An absolute path specifies the exact location of the image on your computer.
Using forward slashes (/) is recommended because they work consistently across platforms and avoid escaping issues in Python strings.
When an image is loaded, OpenCV stores it as a multidimensional NumPy array. Each element in the array represents a pixel value.
import cv2
image = cv2.imread("sample.jpg")
print(type(image))
Output:
<class 'numpy.ndarray'>
This integration with NumPy makes OpenCV both efficient and flexible for image manipulation.
You can determine the height, width, and number of color channels using the shape attribute.
import cv2
image = cv2.imread("sample.jpg")
print(image.shape)
Example output:
(720, 1280, 3)
The values represent:
Always verify the file path before debugging OpenCV code.
None.
In this lesson, you learned how to read images using cv2.imread(), verify successful loading, understand file paths, inspect image dimensions, and see how OpenCV stores images as NumPy arrays. In the next part, you will learn how to display images using OpenCV and Matplotlib, along with the differences between the two visualization methods.
After reading an image successfully, the next step is to display it on the screen. Visualizing images helps you verify that they have been loaded correctly and allows you to observe the effects of image processing operations such as resizing, filtering, cropping, edge detection, and color conversion.
OpenCV provides the cv2.imshow() function to display images in a separate window. In Data Science and Machine Learning projects, developers also use Matplotlib to display images directly inside Jupyter Notebook.
The cv2.imshow() function creates a window and displays the specified image.
Syntax:
cv2.imshow(window_name, image)
Parameters:
cv2.imread().Example:
import cv2
image = cv2.imread("sample.jpg")
cv2.imshow("Original Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
This program opens a new window displaying the image until a key is pressed.
The cv2.waitKey() function pauses the program and waits for keyboard input. Without this function, the image window will close immediately because the program finishes execution.
Example:
cv2.waitKey(0)
A value of 0 means the program waits indefinitely until any key is pressed.
You can also specify a time in milliseconds.
cv2.waitKey(5000)
The above example waits for 5 seconds before continuing execution.
After displaying an image, it is good practice to close all OpenCV windows using:
cv2.destroyAllWindows()
This releases system resources and closes every OpenCV window currently open.
To close only a specific window:
cv2.destroyWindow("Original Image")
OpenCV allows you to display multiple images simultaneously by assigning different window names.
import cv2
image1 = cv2.imread("sample.jpg")
image2 = cv2.imread("sample2.jpg")
cv2.imshow("Image One", image1)
cv2.imshow("Image Two", image2)
cv2.waitKey(0)
cv2.destroyAllWindows()
The cv2.imshow() function may not work properly in Jupyter Notebook because notebooks run inside a web browser. In these cases, Matplotlib is the preferred visualization library.
Example:
import cv2
import matplotlib.pyplot as plt
image = cv2.imread("sample.jpg")
rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.imshow(rgb)
plt.title("Original Image")
plt.axis("off")
plt.show()
Notice that the image is converted from BGR to RGB before displaying it. This ensures that colors appear correctly in Matplotlib.
| Feature | OpenCV | Matplotlib |
|---|---|---|
| Default Color Format | BGR | RGB |
| Works in Jupyter Notebook | Limited | Excellent |
| Interactive Windows | Yes | No |
| Best For | Desktop Applications | Notebooks and Visualization |
Cause: Missing cv2.waitKey().
Solution:
cv2.waitKey(0)
Cause: OpenCV loads images in BGR format, while Matplotlib expects RGB.
Solution:
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
Possible reasons include an incorrect image path, unsupported environment, or using cv2.imshow() inside Jupyter Notebook.
cv2.imshow() for desktop applications.cv2.waitKey() after displaying an image.cv2.destroyAllWindows().
In this lesson, you learned how to display images using cv2.imshow(), understood the role of cv2.waitKey() and cv2.destroyAllWindows(), displayed multiple images, and learned why Matplotlib is the preferred choice for Jupyter Notebook. You also explored common display errors and best practices. In the next part, you will learn how to save images using cv2.imwrite(), explore different image formats and reading modes, and complete the lesson with FAQs and practice exercises.
After processing an image, you will usually want to save the result for later use. Whether you have resized an image, converted it to grayscale, applied filters, or detected objects, OpenCV provides a simple function called cv2.imwrite() to write images to your computer.
The cv2.imwrite() function saves the image in various formats such as JPEG, PNG, BMP, TIFF, and WebP. The output format is automatically determined from the file extension that you specify.
cv2.imwrite(filename, image)
Parameters:
Return Value:
The function returns True if the image is saved successfully and False if the operation fails.
The following example saves the loaded image as a PNG file.
import cv2
image = cv2.imread("sample.jpg")
success = cv2.imwrite("output.png", image)
if success:
print("Image saved successfully.")
else:
print("Failed to save the image.")
You can also save processed images such as grayscale versions.
import cv2
image = cv2.imread("sample.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imwrite("gray_image.jpg", gray)
| Format | Extension | Features |
|---|---|---|
| JPEG | .jpg, .jpeg | Compressed format suitable for photographs. |
| PNG | .png | Lossless compression and transparency support. |
| BMP | .bmp | Uncompressed image with large file size. |
| TIFF | .tiff | High-quality images used in publishing and medical imaging. |
| WebP | .webp | Modern image format offering efficient compression and good quality. |
The cv2.imread() function accepts an optional flag that controls how an image is loaded.
image = cv2.imread("sample.jpg", cv2.IMREAD_COLOR)
Loads the image in color using the BGR color space. This is the default mode.
image = cv2.imread("sample.jpg", cv2.IMREAD_GRAYSCALE)
Loads the image as a single-channel grayscale image, reducing memory usage and processing time.
image = cv2.imread("sample.png", cv2.IMREAD_UNCHANGED)
Loads the image without changing its original format, including the alpha (transparency) channel if present.
| Task | Recommended Mode |
|---|---|
| General image processing | IMREAD_COLOR |
| Edge detection | IMREAD_GRAYSCALE |
| Thresholding | IMREAD_GRAYSCALE |
| Images with transparency | IMREAD_UNCHANGED |
| Machine learning preprocessing | Depends on the model requirements. |
| Feature | JPEG | PNG |
|---|---|---|
| Compression | Lossy | Lossless |
| Image Quality | Good | Excellent |
| Transparency | No | Yes |
| File Size | Smaller | Larger |
| Best For | Photographs | Logos, graphics, screenshots |
cv2.imwrite() to ensure the image was saved.This usually indicates an invalid file path, missing write permissions, or an unsupported file format.
JPEG is suitable for photographs, while PNG is preferred for graphics, diagrams, and images requiring transparency or lossless quality.
Yes. Use cv2.IMREAD_UNCHANGED to preserve the alpha channel.
Most modern OpenCV builds support WebP, provided the library was compiled with WebP support.
cv2.imread() to load images.cv2.imshow() or Matplotlib to display images.cv2.imwrite() to save processed images.cv2.imshow().gray_output.jpg.IMREAD_GRAYSCALE and compare its dimensions with the color version.IMREAD_UNCHANGED and inspect its number of channels.
In this lesson, you learned how to read, display, and save images using OpenCV. You explored the cv2.imread(), cv2.imshow(), cv2.waitKey(), cv2.destroyAllWindows(), and cv2.imwrite() functions, understood different image reading modes, compared common image formats, and learned best practices for managing image files. These essential skills form the foundation for every OpenCV project. In the next lesson, you will begin performing basic image operations such as resizing, cropping, rotating, and flipping images.