Once you have installed OpenCV, the first step in image processing is learning how to
read, write, and display images. OpenCV provides simple functions for these tasks:
cv2.imread(), cv2.imwrite(), and cv2.imshow().
Use cv2.imread() to read an image. By default, OpenCV loads images in BGR format.
import cv2
# Read an image from file
img = cv2.imread("sample.jpg")
# Check if image is loaded
if img is None:
print("Error: Image not found!")
else:
print("Image loaded successfully!")
To display an image, use cv2.imshow(). You must also include cv2.waitKey()
to keep the window open until a key is pressed.
cv2.imshow("My Image", img) # Window title + image
cv2.waitKey(0) # Wait until a key is pressed
cv2.destroyAllWindows() # Close all windows
Use cv2.imwrite() to save an image to your system.
# Save the image as PNG
cv2.imwrite("output.png", img)
The cv2.imread() function supports different modes:
cv2.IMREAD_COLOR (default) – Loads image in color (BGR).cv2.IMREAD_GRAYSCALE – Loads image in grayscale (single channel).cv2.IMREAD_UNCHANGED – Loads image as is (including alpha channel if present).
gray = cv2.imread("sample.jpg", cv2.IMREAD_GRAYSCALE)
cv2.imshow("Grayscale Image", gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite("output_gray.jpg", gray)
✅ In this lesson, you learned how to read, display, and save images with OpenCV.
This forms the foundation of image processing tasks.
👉 Next, we will explore basic image operations such as resize, crop, rotate, and flip.
