CV2 in Python --- 2 part of 5

Getting Started with OpenCV in Python – Part 2

📸 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

FlagDescription
cv2.IMREAD_COLORLoads in color (default)
cv2.IMREAD_GRAYSCALELoads as grayscale
cv2.IMREAD_UNCHANGEDLoads 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

IssueCauseFix
NoneType errorImage not foundCheck filename and path
Blank windowMissing waitKey()Add cv2.waitKey(0)
Window closes instantlyNo delayUse 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.

⌨️ Made with Python & ❤️ by Champak Roy | Part 2 of 5

Post a Comment

0 Comments

Me