Skip to content

Image Processing

🧱 2. Image Processing Basics

🎨 2.1 Color Spaces

Convert between color spaces using cv2.cvtColor.

import cv2
img = cv2.imread("image.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("Grayscale", gray)
cv2.waitKey(0)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
cv2.imshow("HSV", hsv)
cv2.waitKey(0)

🖍️ 2.2 Drawing Functions

Draw shapes and text onto images.

img = cv2.imread("image.jpg")
cv2.line(img, (50, 50), (200, 50), (0, 255, 0), 2)
cv2.rectangle(img, (50, 100), (200, 200), (255, 0, 0), 3)
cv2.imshow("Shapes", img)
cv2.waitKey(0)
cv2.circle(img, (150, 300), 50, (0, 0, 255), -1)
cv2.putText(img, "OpenCV", (50, 400), cv2.FONT_HERSHEY_SIMPLEX, 1.2, (255,255,255), 2)
cv2.imshow("Circles and Text", img)
cv2.waitKey(0)

✂️ 2.3 Image Transformations

Resize, crop, rotate, or flip images.

resized = cv2.resize(img, (300, 300))
cropped = img[100:300, 100:300]
cv2.imshow("Resized", resized)
cv2.imshow("Cropped", cropped)
cv2.waitKey(0)
rotated = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
flipped = cv2.flip(img, 1)  # Horizontal
cv2.imshow("Rotated", rotated)
cv2.imshow("Flipped", flipped)
cv2.waitKey(0)

🔲 2.4 Thresholding

Convert images to binary using fixed or adaptive methods.

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
cv2.imshow("Threshold", thresh)
cv2.waitKey(0)
_, thresh_otsu = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
cv2.imshow("Otsu Threshold", thresh_otsu)
cv2.waitKey(0)

🌫️ 2.5 Image Filtering

Smooth or denoise images using various filters.

blurred = cv2.GaussianBlur(img, (5, 5), 0)
cv2.imshow("Gaussian Blur", blurred)
cv2.waitKey(0)
median = cv2.medianBlur(img, 5)
cv2.imshow("Median Blur", median)
cv2.waitKey(0)
bilateral = cv2.bilateralFilter(img, 9, 75, 75)
cv2.imshow("Bilateral Filter", bilateral)
cv2.waitKey(0)