📸 OpenCV in Python – Part 2
Reading, Displaying, and Writing Images
📘 What You’ll Learn
In this part, we’ll focus on:
- Reading an image in color, grayscale, and unchanged modes
- Displaying images in a window
- Saving images to disk in different formats
🖼️ cv2.imread()
Syntax:
cv2.imread(filename, flags)
Read Modes
Flag | Description |
---|---|
cv2.IMREAD_COLOR | Loads in color (default) |
cv2.IMREAD_GRAYSCALE | Loads as grayscale |
cv2.IMREAD_UNCHANGED | Loads as-is, including alpha channel |
import cv2
color_img = cv2.imread("sample.jpg", cv2.IMREAD_COLOR)
gray_img = cv2.imread("sample.jpg", cv2.IMREAD_GRAYSCALE)
unchanged_img = cv2.imread("sample.jpg", cv2.IMREAD_UNCHANGED)
🪟 cv2.imshow()
Displays an image in a window.
cv2.imshow("Color Image", color_img)
cv2.imshow("Grayscale Image", gray_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
💾 cv2.imwrite()
Saves an image to a file.
cv2.imwrite("saved_gray.png", gray_img)
cv2.imwrite("saved_color.jpg", color_img)
⚠️ Common Errors
Issue | Cause | Fix |
---|---|---|
NoneType error | Image not found | Check filename and path |
Blank window | Missing waitKey() | Add cv2.waitKey(0) |
Window closes instantly | No delay | Use waitKey properly |
✅ Full Working Example
import cv2
img_color = cv2.imread("sample.jpg", cv2.IMREAD_COLOR)
img_gray = cv2.imread("sample.jpg", cv2.IMREAD_GRAYSCALE)
cv2.imshow("Original", img_color)
cv2.imshow("Grayscale", img_gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite("copy_color.jpg", img_color)
cv2.imwrite("copy_gray.png", img_gray)
📚 Next Up
In Part 3, we will explore image processing basics: resizing, cropping, and color space transformations.
0 Comments