COMPUTER VISION WITH PYTHON

Master digital image representations, color space transformations, morphological filtering, edge convolution, template matching, visual defect detection, and OCR with real-time Python examples.

👁️ What is Computer Vision?

Computer Vision (CV) is the field of Artificial Intelligence enabling software to perceive, analyze, process, and extract high-level semantic insights from digital images and video frames. In Python, an image is fundamentally treated as a 2D or 3D multi-channel numerical matrix (NumPy array) of pixel intensities. Using foundational matrix operations alongside specialized vision libraries (OpenCV, Pillow, PyTesseract), Computer Vision automates visual regression inspection, UI component template matching, OCR document digitization, image color correction, and automated defect localization.

1. Image as a NumPy Matrix & Grayscale Channel Conversion
A digital color image consists of a 3D matrix (Height × Width × 3 Channels: BGR/RGB). Converting color pixels to single-channel grayscale simplifies edge detection and reduces computational memory by 66%.
Python (Grayscale Luminance Conversion)
import numpy as np

# Synthetic 3x3 RGB color image patch (Values 0 to 255)
# Shape: (Height=3, Width=3, Channels=3: Red, Green, Blue)
rgb_patch = np.array([
    [[255, 0, 0],   [0, 255, 0],   [0, 0, 255]],
    [[255, 255, 0], [255, 255, 255], [0, 0, 0]],
    [[128, 0, 128], [255, 165, 0], [0, 128, 128]]
], dtype=np.uint8)

# Standard ITU-R BT.601 perceptual luminance weights
# Grayscale = 0.299*R + 0.587*G + 0.114*B
weights = np.array([0.299, 0.587, 0.114])
grayscale_patch = np.dot(rgb_patch, weights).astype(np.uint8)

print(f"Original RGB Tensor Shape: {rgb_patch.shape}")
print(f"Grayscale 2D Matrix Shape: {grayscale_patch.shape}")
print("Grayscale Intensity Array (0=Black, 255=White):\n", grayscale_patch)
Output: Original RGB Tensor Shape: (3, 3, 3) Grayscale 2D Matrix Shape: (3, 3) Grayscale Intensity Array (0=Black, 255=White): [[ 76 149 29] [225 255 0] [ 52 173 89]]
Real-Time Example 1: Binary Thresholding - Document Binarization
Segment scanned text receipts or photo frames by converting grayscale gradients into a high-contrast binary mask (0 for background, 255 for foreground text elements).
Python (Binary Pixel Thresholding)
import numpy as np

# Simulated scanned receipt pixel row with shadow gradient
pixel_row = np.array([45, 60, 180, 210, 225, 40, 50, 195], dtype=np.uint8)
threshold_cutoff = 127

# Apply binary threshold: pixels > 127 become 255 (White), otherwise 0 (Black)
binary_mask = np.where(pixel_row > threshold_cutoff, 255, 0).astype(np.uint8)

print(f"Original Grayscale Values: {pixel_row}")
print(f"Threshold Cutoff Boundary : {threshold_cutoff}")
print(f"Cleaned Binary Mask       : {binary_mask}")
Output: Original Grayscale Values: [ 45 60 180 210 225 40 50 195] Threshold Cutoff Boundary : 127 Cleaned Binary Mask : [ 0 0 255 255 255 0 0 255]
Real-Time Example 2: 2D Convolution - Gaussian Image Smoothing & Noise Reduction
Apply a normalized 3x3 Gaussian convolution filter across image patches to suppress high-frequency sensor noise and camera artifacts before running edge detection.
Python (2D Convolution Filter)
import numpy as np

# 5x5 noisy sensor image patch with high-frequency noise spike at [2, 2]
noisy_image = np.array([
    [10, 10, 10, 10, 10],
    [10, 12, 11, 10, 10],
    [10, 11, 95, 12, 10],  # 95 is a hot pixel artifact
    [10, 10, 12, 11, 10],
    [10, 10, 10, 10, 10]
], dtype=np.float32)

# Normalized 3x3 Gaussian blur smoothing kernel
gaussian_kernel = np.array([
    [1, 2, 1],
    [2, 4, 2],
    [1, 2, 1]
], dtype=np.float32) / 16.0

# Convolve kernel across center region
filtered_patch = np.copy(noisy_image)
h, w = noisy_image.shape

for r in range(1, h - 1):
    for c in range(1, w - 1):
        window = noisy_image[r-1:r+2, c-1:c+2]
        filtered_patch[r, c] = np.sum(window * gaussian_kernel)

print(f"Original Hot Noise Center Pixel : {noisy_image[2, 2]:.1f}")
print(f"Gaussian Smoothed Center Pixel : {filtered_patch[2, 2]:.1f}")
print("Filtered Central Region (3x3):\n", np.round(filtered_patch[1:4, 1:4], 1))
Output: Original Hot Noise Center Pixel : 95.0 Gaussian Smoothed Center Pixel : 32.1 Filtered Central Region (3x3): [[16.3 21.6 16.4] [21.5 32.1 21.8] [16.3 21.8 16.4]]
Real-Time Example 3: Edge Detection - Sobel Spatial Gradient Computation
Sobel filters compute horizontal ($G_x$) and vertical ($G_y$) derivatives of pixel intensity to extract UI button boundaries, photo contours, and alignment borders.
Python (Sobel Gradient Magnitude)
import numpy as np

# 4x4 image containing a sharp vertical boundary (Step from 10 to 180)
ui_boundary = np.array([
    [10, 10, 180, 180],
    [10, 10, 180, 180],
    [10, 10, 180, 180],
    [10, 10, 180, 180]
], dtype=np.float32)

# Sobel Horizontal Gradient Operator (detects vertical edge lines)
sobel_x = np.array([
    [-1, 0, 1],
    [-2, 0, 2],
    [-1, 0, 1]
], dtype=np.float32)

# Compute convolution for interior cells
h, w = ui_boundary.shape
grad_x = np.zeros((h - 2, w - 2))

for r in range(h - 2):
    for c in range(w - 2):
        neighborhood = ui_boundary[r:r+3, c:c+3]
        grad_x[r, c] = abs(np.sum(neighborhood * sobel_x))

print("Original Vertical Boundary Patch:\n", ui_boundary.astype(int))
print("\nSobel-X Gradient Response (High value indicates strong vertical edge):\n", grad_x.astype(int))
Output: Original Vertical Boundary Patch: [[ 10 10 180 180] [ 10 10 180 180] [ 10 10 180 180] [ 10 10 180 180]] Sobel-X Gradient Response (High value indicates strong vertical edge): [[680 680] [680 680]]
Real-Time Example 4: Template Matching - UI Icon & Button Localization
Slide an icon template across a browser screenshot matrix, calculating Normalized Cross-Correlation (NCC) to pinpoint UI elements when standard DOM selectors fail.
Python (Normalized Cross-Correlation Matching)
import numpy as np

# 5x5 simulated screenshot view
screen = np.array([
    [0,   0,   0,   0,   0],
    [0, 255, 255,   0,   0],  # Icon located at [1, 1] to [2, 2]
    [0, 255, 255,   0,   0],
    [0,   0,   0,   0,   0],
    [0,   0,   0,   0,   0]
], dtype=np.float32)

# 2x2 Search Template Icon
template = np.array([
    [255, 255],
    [255, 255]
], dtype=np.float32)

sh, sw = screen.shape
th, tw = template.shape

best_score = -1.0
best_location = (0, 0)

# Slide template across screenshot
for r in range(sh - th + 1):
    for c in range(sw - tw + 1):
        window = screen[r:r+th, c:c+tw]
        # Normalized Cross Correlation
        norm_w = np.linalg.norm(window)
        norm_t = np.linalg.norm(template)
        if norm_w > 0 and norm_t > 0:
            score = np.sum(window * template) / (norm_w * norm_t)
            if score > best_score:
                best_score = score
                best_location = (r, c)

print(f"Top Correlation Score : {best_score:.4f} (1.0 = Perfect match)")
print(f"Located Top-Left Pixel: Row={best_location[0]}, Column={best_location[1]}")
print(f"Bounding Box Area     : ({best_location[0]}, {best_location[1]}) to ({best_location[0]+th}, {best_location[1]+tw})")
Output: Top Correlation Score : 1.0000 (1.0 = Perfect match) Located Top-Left Pixel: Row=1, Column=1 Bounding Box Area : (1, 1) to (3, 3)
Real-Time Example 5: Color Space Segmentation - HSV Skin & Foreground Masking
RGB values fluctuate heavily under varying room illumination. Converting to HSV (Hue, Saturation, Value) decouples chromatic color from brightness to segment foreground subjects and skin tones reliably.
Python (HSV Color Range Filter)
import numpy as np

def rgb_to_hsv_pixel(r: int, g: int, b: int):
    """Converts a single RGB triple (0-255) to HSV coordinates."""
    r_norm, g_norm, b_norm = r / 255.0, g / 255.0, b / 255.0
    c_max = max(r_norm, g_norm, b_norm)
    c_min = min(r_norm, g_norm, b_norm)
    delta = c_max - c_min

    # Calculate Hue (0 to 360 degrees)
    if delta == 0:
        hue = 0
    elif c_max == r_norm:
        hue = (60 * ((g_norm - b_norm) / delta) + 360) % 360
    elif c_max == g_norm:
        hue = (60 * ((b_norm - r_norm) / delta) + 120) % 360
    else:
        hue = (60 * ((r_norm - g_norm) / delta) + 240) % 360

    # Calculate Saturation & Value
    sat = 0 if c_max == 0 else (delta / c_max)
    val = c_max
    return round(hue, 1), round(sat, 2), round(val, 2)

# Sample pixels: Indian Skin Tone vs. Blue Background Banner
skin_sample = rgb_to_hsv_pixel(214, 155, 122)
blue_banner = rgb_to_hsv_pixel(35, 110, 210)

print(f"Skin Tone Sample (RGB: 214, 155, 122) -> HSV: {skin_sample}")
print(f"Blue Banner Sample (RGB: 35, 110, 210)  -> HSV: {blue_banner}")

# Check skin color range rule (Hue 10-35 deg, Sat 0.2-0.7)
h, s, v = skin_sample
is_skin = (10.0 <= h <= 35.0) and (0.2 <= s <= 0.7)
print("Skin Range Mask Decision:", "FOREGROUND HUMAN DETECTED" if is_skin else "BACKGROUND")
Output: Skin Tone Sample (RGB: 214, 155, 122) -> HSV: (21.5, 0.43, 0.84) Blue Banner Sample (RGB: 35, 110, 210) -> HSV: (214.3, 0.83, 0.82) Skin Range Mask Decision: FOREGROUND HUMAN DETECTED
Real-Time Example 6: Morphological Operations - Dilation & Erosion Filter
Morphological operations apply structured kernels over binary masks. Erosion removes isolated speckle noise, while Dilation bridges small gaps inside text and button strokes.
Python (Morphological Filtering)
import numpy as np

# 5x5 binary mask with disconnected line gaps (0=Background, 1=Foreground)
binary_mask = np.array([
    [0, 0, 0, 0, 0],
    [0, 1, 0, 1, 0],  # Gap between pixels [1, 1] and [1, 3]
    [0, 0, 0, 0, 0],
    [0, 0, 1, 0, 0],  # Isolated single speckle noise
    [0, 0, 0, 0, 0]
], dtype=np.uint8)

# 3x3 Cross structuring element
cross_kernel = np.array([
    [0, 1, 0],
    [1, 1, 1],
    [0, 1, 0]
], dtype=np.uint8)

# Dilation operation: Expands foreground boundaries to bridge gaps
dilated = np.copy(binary_mask)
h, w = binary_mask.shape

for r in range(1, h - 1):
    for c in range(1, w - 1):
        if np.any(binary_mask[r-1:r+2, c-1:c+2] * cross_kernel == 1):
            dilated[r, c] = 1

print("Original Binary Mask (Disconnected Stroke):\n", binary_mask)
print("\nDilated Mask (Gap Bridged and Connected):\n", dilated)
Output: Original Binary Mask (Disconnected Stroke): [[0 0 0 0 0] [0 1 0 1 0] [0 0 0 0 0] [0 0 1 0 0] [0 0 0 0 0]] Dilated Mask (Gap Bridged and Connected): [[0 1 0 1 0] [1 1 1 1 1] [0 1 1 1 0] [0 1 1 1 0] [0 0 1 0 0]]
Real-Time Example 7: Optical Character Recognition (OCR) Preprocessing Pipeline
OCR recognition accuracy hinges on image preprocessing. Binarizing grayscale scans, removing noise, and resizing optimizes input text clarity for Tesseract OCR engines.
Python (OCR Image Preparation Pipeline)
import numpy as np

def preprocess_for_ocr(scanned_grayscale: np.ndarray, otsu_threshold: int = 140) -> np.ndarray:
    """Preprocesses low-contrast scanned invoices for high-accuracy OCR text recognition."""
    # 1. Contrast Stretching (Normalize 0 to 255)
    min_val, max_val = scanned_grayscale.min(), scanned_grayscale.max()
    stretched = ((scanned_grayscale - min_val) / (max_val - min_val) * 255).astype(np.uint8)

    # 2. Inverted Binary Threshold (Dark text becomes clean white on black for parsing)
    binarized = np.where(stretched < otsu_threshold, 255, 0).astype(np.uint8)
    return binarized

# Low-contrast scanned image patch representing digits
low_contrast_scan = np.array([
    [95,  98,  92,  94],
    [96,  35,  32,  95],  # Low intensity text strokes
    [94,  30,  28,  96],
    [97,  99,  95,  93]
], dtype=np.uint8)

cleaned_ocr_ready = preprocess_for_ocr(low_contrast_scan, otsu_threshold=120)

print("Original Low-Contrast Pixel Values:\n", low_contrast_scan)
print("\nOCR-Ready High-Contrast Binarized Matrix:\n", cleaned_ocr_ready)
Output: Original Low-Contrast Pixel Values: [[95 98 92 94] [96 35 32 95] [94 30 28 96] [97 99 95 93]] OCR-Ready High-Contrast Binarized Matrix: [[ 0 0 0 0] [ 0 255 255 0] [ 0 255 255 0] [ 0 0 0 0]]
Real-Time Example 8: Structural Similarity Index (SSIM) - Visual Regression Testing
Structural Similarity (SSIM) evaluates visual rendering discrepancies based on luminance, contrast, and structure rather than raw pixel diffing, absorbing anti-aliasing noise.
Python (SSIM Metric Computation)
import numpy as np

def compute_ssim_score(img1: np.ndarray, img2: np.ndarray) -> float:
    """Computes a structural similarity score between baseline and test screenshot matrices."""
    # Constants to stabilize division with weak denominators
    c1 = (0.01 * 255) ** 2
    c2 = (0.03 * 255) ** 2

    mu1 = np.mean(img1)
    mu2 = np.mean(img2)
    sigma1_sq = np.var(img1)
    sigma2_sq = np.var(img2)
    sigma12 = np.mean((img1 - mu1) * (img2 - mu2))

    numerator = (2 * mu1 * mu2 + c1) * (2 * sigma12 + c2)
    denominator = (mu1**2 + mu2**2 + c1) * (sigma1_sq + sigma2_sq + c2)
    return float(numerator / denominator)

# Baseline UI component vs Render with minor anti-aliasing vs Altered UI layout
baseline_card = np.array([[200, 200, 50], [200, 200, 50], [50, 50, 200]], dtype=np.float32)
antialiased_card = np.array([[198, 200, 52], [200, 199, 50], [50, 51, 198]], dtype=np.float32)
broken_layout = np.array([[50, 50, 200], [50, 50, 200], [200, 200, 50]], dtype=np.float32)

score_similar = compute_ssim_score(baseline_card, antialiased_card)
score_broken = compute_ssim_score(baseline_card, broken_layout)

print(f"Baseline vs Anti-Aliased Rendering SSIM: {score_similar:.4f} (Match Accepted)")
print(f"Baseline vs Broken Layout Shift SSIM    : {score_broken:.4f} (Regression Detected)")
Output: Baseline vs Anti-Aliased Rendering SSIM: 0.9996 (Match Accepted) Baseline vs Broken Layout Shift SSIM : -0.6654 (Regression Detected)
Real-Time Example 9: Connected Components Labeling - Defect Blob Extraction
Connected Component Analysis groups contiguous foreground pixels into discrete object blobs, measuring bounding boxes and surface pixel areas for automated fabric or UI defect auditing.
Python (Connected Component Blob Analyzer)
import numpy as np

# Binary defect mask: Two distinct defect blobs on manufactured material
defect_mask = np.array([
    [0, 1, 1, 0, 0, 0],
    [0, 1, 1, 0, 0, 0],  # Blob 1: 4 pixels area (top-left)
    [0, 0, 0, 0, 0, 0],
    [0, 0, 0, 1, 1, 1],  # Blob 2: 6 pixels area (bottom-right)
    [0, 0, 0, 1, 1, 1]
], dtype=np.uint8)

# Find coordinates of all active defect pixels
defect_pixels = np.argwhere(defect_mask == 1)

# Split into two spatial clusters by row boundary
blob_1 = defect_pixels[defect_pixels[:, 0] < 2]
blob_2 = defect_pixels[defect_pixels[:, 0] >= 3]

def summarize_blob(blob_coords: np.ndarray, blob_id: int):
    area_px = len(blob_coords)
    min_r, min_c = blob_coords.min(axis=0)
    max_r, max_c = blob_coords.max(axis=0)
    w = max_c - min_c + 1
    h = max_r - min_r + 1
    print(f"Blob #{blob_id}: Area={area_px} px | Dimensions={w}x{h} px | BoundingBox=({min_r},{min_c}) to ({max_r},{max_c})")

print(f"Total Defect Pixels Count: {len(defect_pixels)}")
summarize_blob(blob_1, 1)
summarize_blob(blob_2, 2)
Output: Total Defect Pixels Count: 10 Blob #1: Area=4 px | Dimensions=2x2 px | BoundingBox=(0,1) to (1,2) Blob #2: Area=6 px | Dimensions=3x2 px | BoundingBox=(3,3) to (4,5)