Wednesday, November 19, 2025

πŸ“Έ Image Processing with Python – Complete Guide

 Image Processing means converting, enhancing, analyzing, or transforming images using computational techniques.

Python is widely used for image processing because of libraries like:

  • NumPy (fast array operations)

  • PIL/Pillow (basic image manipulation)

  • OpenCV (advanced computer vision)

  • Matplotlib (display images)


⭐ 1. Install Required Libraries

pip install pillow opencv-python numpy matplotlib

⭐ 2. Load and Display an Image

Using PIL

from PIL import Image import matplotlib.pyplot as plt img = Image.open("image.jpg") plt.imshow(img) plt.axis('off')

Using OpenCV

Note: OpenCV loads images in BGR format (not RGB).

import cv2 import matplotlib.pyplot as plt img = cv2.imread("image.jpg") img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) plt.imshow(img_rgb) plt.axis("off")

⭐ 3. Convert Image to Grayscale

Using PIL + NumPy

import numpy as np from PIL import Image img = Image.open("image.jpg") img_arr = np.array(img) gray = np.dot(img_arr[...,:3], [0.299, 0.587, 0.114]) plt.imshow(gray, cmap='gray') plt.axis("off")

What is happening?

  • RGB → turned into a single intensity value

  • Weighted formula gives grayscale


⭐ 4. Resize an Image

Using PIL

resized = img.resize((300, 300)) plt.imshow(resized) plt.axis('off')

Using OpenCV

resized = cv2.resize(img_rgb, (300, 300)) plt.imshow(resized) plt.axis('off')

⭐ 5. Rotate an Image

Using PIL

rotated = img.rotate(45) plt.imshow(rotated) plt.axis('off')

Using OpenCV

(h, w) = img_rgb.shape[:2] matrix = cv2.getRotationMatrix2D((w/2, h/2), 45, 1) rotated = cv2.warpAffine(img_rgb, matrix, (w, h)) plt.imshow(rotated) plt.axis('off')

⭐ 6. Flipping an Image

flip_h = cv2.flip(img_rgb, 1) # horizontal flip_v = cv2.flip(img_rgb, 0) # vertical plt.imshow(flip_h) plt.axis('off')

⭐ 7. Edge Detection (Canny Algorithm)

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 100, 200) plt.imshow(edges, cmap='gray') plt.axis('off')

What it does:

  • Detects borders/edges in the image

  • Used in object detection, OCR, robotics


⭐ 8. Image Thresholding (Black & White)

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) _, thresh = cv2.threshold(gray, 120, 255, cv2.THRESH_BINARY) plt.imshow(thresh, cmap='gray') plt.axis('off')

⭐ 9. Blurring / Smoothing

Gaussian Blur

blur = cv2.GaussianBlur(img_rgb, (15, 15), 0) plt.imshow(blur) plt.axis('off')

Mean Blur

blur = cv2.blur(img_rgb, (10, 10)) plt.imshow(blur) plt.axis('off')

⭐ 10. Image Histogram (Intensity Distribution)

import cv2 import matplotlib.pyplot as plt gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) plt.hist(gray.ravel(), 256) plt.show()

⭐ 11. Morphological Operations

Used in noise removal, object extraction.

Erosion

kernel = np.ones((5,5), np.uint8) eroded = cv2.erode(gray, kernel, iterations=1)

Dilation

dilated = cv2.dilate(gray, kernel, iterations=1)

⭐ 12. Image Masking (Focus on a Region)

mask = np.zeros(img_rgb.shape[:2], dtype="uint8") mask[100:300, 100:300] = 255 masked = cv2.bitwise_and(img_rgb, img_rgb, mask=mask) plt.imshow(masked) plt.axis('off')

⭐ 13. Image Contour Detection (Detect Shapes)

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) _, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY) contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(img_rgb, contours, -1, (255, 0, 0), 2) plt.imshow(img_rgb) plt.axis('off')

⭐ 14. Face Detection Using Haarcascade

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x,y,w,h) in faces: cv2.rectangle(img_rgb,(x,y),(x+w,y+h),(255,0,0),2) plt.imshow(img_rgb) plt.axis('off')

⭐ 15. Image Segmentation using K-Means

pixels = img_rgb.reshape((-1, 3)) pixels = np.float32(pixels) k = 4 criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2) _, labels, centers = cv2.kmeans(pixels, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS) centers = np.uint8(centers) segmented = centers[labels.flatten()] segmented = segmented.reshape(img_rgb.shape) plt.imshow(segmented) plt.axis('off')

No comments:

Post a Comment

Machine Learning with Python : Scratch to Advanced

https://claude.ai/public/artifacts/d515bb8c-40dd-4d9a-9010-beb96f6aa4e5