Go Back
Pyodide WASM • OpenCV
Active Environment:
Python 3.11 • OpenCV 4.x (Pyodide WASM)
Default Sample Image (/input.jpg)
exp1_grayscale_conversion.py
1
OpenCV + Pyodide WASM
Ctrl+Enter to execute
Processed Image & Video Results
0 Outputs

No Processed Media Yet

Click "Run Code" to execute your OpenCV script with cv2_imshow(), cv2.imshow(), or video processing. Output frames and videos render live here!

💡 40 EXPERIMENTS Click "Load CV Code" above to load ready-to-run university syllabus experiments.
Ready 0ms
Pyodide WebAssembly Sandbox

📖 Computer Vision & Digital Image Processing Laboratory Manual

Master the mathematical matrix representations, 2D spatial convolution kernels, gradient-based edge operators, morphological transformations, feature extraction descriptors, and university laboratory OpenCV Python experiments. Written for undergraduate computer science and artificial intelligence engineering students.

🖼️ Module 1: Digital Image Processing Fundamentals & Matrix Representation

Spatial Sampling • Intensity Quantization • Color Channels

🎯 Learning Objectives

  • Understand digital image formation from continuous light irradiance to discrete pixel arrays.
  • Differentiate between Binary, Grayscale, and multi-channel RGB/BGR color spaces.
  • Formulate spatial sampling resolution and intensity quantization levels (\(L = 2^k\)).
  • Analyze intensity histograms, dynamic range, and global contrast stretching.

🌍 Real-World Applications

  • Medical MRI and CT scan slice reconstruction, satellite multispectral remote sensing.
  • Display engine rendering pipelines, HDR photography, and document digitization.

A. Digital Images as 2D Discrete Intensity Matrices

Mathematically, a monochrome continuous image is represented as a 2D continuous light intensity function \(f(x, y)\), where \((x, y)\) denotes spatial Cartesian coordinates and \(f\) represents the radiometric amplitude (radiance/reflectance) at that coordinate. To store and process an image digitally, it must undergo two fundamental discretization processes:

  • Spatial Sampling: Discretizing the spatial domain coordinates \((x, y)\) into an \(M \times N\) rectangular matrix grid of picture elements (pixels). An image of resolution \(1920 \times 1080\) contains \(M = 1080\) rows and \(N = 1920\) columns (\(2,073,600\) pixels).
  • Intensity Quantization: Discretizing continuous light amplitude \(f(x, y)\) into a finite integer set of \(L = 2^k\) discrete grey levels. In standard 8-bit quantization (\(k = 8\)), each pixel brightness is bounded between \(0\) (absolute black / zero irradiance) and \(255\) (pure white / saturation).

B. Color Spaces: RGB vs. BGR vs. Grayscale

Image Mode Channels (\(C\)) Bit Depth Tensor Shape (\(H \times W \times C\)) Mathematical Formula & Channel Structure
Binary (1-Bit) 1 1 bit/pixel \(M \times N \times 1\) \(f(x, y) \in \{0, 1\}\). Ideal for document masks, OCR binarization, and morphological footprints.
Grayscale (8-Bit) 1 8 bits/pixel \(M \times N \times 1\) \(0 \le f(x, y) \le 255\). Represents luminous intensity without hue. Derived via ITU-R BT.601:
Gray = 0.299*R + 0.587*G + 0.114*B
RGB Color 3 24 bits/pixel \(M \times N \times 3\) Additive primary color model: Red, Green, Blue channels each spanning \([0, 255]\) (\(16.7\text{ million}\) colors).
BGR (OpenCV Default) 3 24 bits/pixel \(M \times N \times 3\) OpenCV historically stores color channels in Blue-Green-Red order due to legacy hardware framegrabbers. Must convert via cv2.cvtColor(img, cv2.COLOR_BGR2RGB) when plotting with Matplotlib.

C. Image Histograms & Contrast Enhancement

An image histogram is a discrete statistical frequency distribution plot representing the number of pixels \(n_k\) at each intensity level \(r_k \in [0, L-1]\):

\[p(r_k) = \frac{n_k}{M \times N}, \quad k = 0, 1, \dots, L-1\] Where \(p(r_k)\) is the empirical probability of occurrence of intensity level \(r_k\).
• Low Contrast: Histogram is narrowly clustered into a small sub-range of grey levels.
• Histogram Equalization: Transforms the input image via the cumulative distribution function (CDF) \(s_k = T(r_k) = (L-1) \sum_{j=0}^k p(r_j)\), spreading out the most frequent intensity values uniformly to maximize visual dynamic contrast.

🌊 Module 2: Image Filtering, Spatial Kernels & 2D Discrete Convolution

Linear Spatial Filtering • Gaussian Smoothing • Median Denoising

🎯 Learning Objectives

  • Derive the 2D discrete spatial convolution mathematical equation.
  • Construct smoothing kernels: Box Mean Filter and 2D Gaussian Kernel.
  • Apply non-linear Median Filtering to eliminate non-Gaussian salt-and-pepper impulse noise.
  • Design second-derivative spatial sharpening filters using the discrete Laplacian mask.

🌍 Real-World Applications

  • Pre-filtering noise prior to optical edge detection and deep learning classification.
  • Computational photography portrait blur (bokeh) and unsharp masking image enhancement.

A. 2D Discrete Convolution Formula

Filtering an image \(f(x, y)\) with an odd-sized \((2a+1) \times (2b+1)\) spatial filter kernel \(w(s, t)\) computes a linear weighted sum of neighboring pixel intensities:

\[g(x, y) = f(x, y) * w(x, y) = \sum_{s=-a}^a \sum_{t=-b}^b f(x - s, y - t) \, w(s, t)\] In spatial correlation (commonly utilized in deep neural network layers), the kernel is slid directly across the matrix without 180-degree reflection. For symmetric kernels (such as Gaussian and Box filters), convolution and correlation produce mathematically identical output matrices.

B. Primary Spatial Kernel Masks

Filter Type Kernel Dimension Matrix Formulation Filtering Properties & Impulse Response
Box Mean Filter \(3 \times 3\) \(\frac{1}{9} \begin{bmatrix} 1 & 1 & 1 \\ 1 & 1 & 1 \\ 1 & 1 & 1 \end{bmatrix}\) Linear low-pass filter. Blurs image by averaging local neighborhood. High frequencies (edges) are softened. Sum of weights equals 1.0 (preserves overall luminosity).
Gaussian Blur Filter \(3 \times 3\) (\(\sigma \approx 1\)) \(\frac{1}{16} \begin{bmatrix} 1 & 2 & 1 \\ 2 & 4 & 2 \\ 1 & 2 & 1 \end{bmatrix}\) Isotropic 2D Gaussian distribution \(G(x,y) = \frac{1}{2\pi\sigma^2} e^{-\frac{x^2+y^2}{2\sigma^2}}\). Weights decrease with radial distance from the center, producing natural smoothing without severe box artifacts.
Sharpening Filter \(3 \times 3\) \(\begin{bmatrix} 0 & -1 & 0 \\ -1 & 5 & -1 \\ 0 & -1 & 0 \end{bmatrix}\) High-pass enhancement. Enhances spatial intensity discontinuities by subtracting local Laplacian second derivative from original center pixel.
Median Filter Non-Linear \(\text{median}\{f(x+s, y+t)\}\) Sorts all pixel values in local window and replaces the center pixel with the median. Extremely effective at removing salt-and-pepper noise without blurring sharp edge transitions.

C. Worked Numerical 2D Convolution Example

Sample Calculation: Compute the convolved output pixel \(g(2, 2)\) when filtering the center pixel of this \(3 \times 3\) image patch \(P\) with sharpening kernel \(K\): \[P = \begin{bmatrix} 10 & 20 & 10 \\ 20 & \mathbf{50} & 20 \\ 10 & 20 & 10 \end{bmatrix}, \quad K = \begin{bmatrix} 0 & -1 & 0 \\ -1 & 5 & -1 \\ 0 & -1 & 0 \end{bmatrix}\]
Calculation: \[g(2, 2) = (10 \times 0) + (20 \times (-1)) + (10 \times 0) + (20 \times (-1)) + (50 \times 5) + (20 \times (-1)) + (10 \times 0) + (20 \times (-1)) + (10 \times 0)\] \[g(2, 2) = 0 - 20 + 0 - 20 + 250 - 20 + 0 - 20 + 0 = 250 - 80 = \mathbf{170}\] Result: The center intensity increases from 50 to 170, emphasizing the local high-frequency contrast relative to its surrounding darker neighbors.

⚡ Module 3: Edge Detection Algorithms, Image Gradients & Canny Pipeline

1st & 2nd Derivatives • Sobel Operators • Canny 5-Stage Architecture

🎯 Learning Objectives

  • Formulate first-order directional gradients (\(G_x, G_y\)), gradient magnitude \(M(x, y)\), and edge orientation angle \(\theta\).
  • Apply Sobel, Prewitt, and Laplacian of Gaussian (LoG) spatial masks.
  • Trace the complete 5-stage Canny Edge Detection pipeline: smoothing, gradient magnitude, non-maximum suppression, double thresholding, and hysteresis edge tracking.

🌍 Real-World Applications

  • Lane detection in Advanced Driver Assistance Systems (ADAS).
  • Industrial assembly inspection, document boundary scanning, barcode and QR code localization.

A. Image Gradients & First-Order Partial Derivatives

An edge is a significant local discontinuity in pixel brightness. In calculus, continuous edges correspond to extrema of the first derivative. For discrete 2D digital images, gradients are calculated along horizontal and vertical axes:

\[\nabla f = \begin{bmatrix} G_x \\ G_y \end{bmatrix} = \begin{bmatrix} \frac{\partial f}{\partial x} \\ \frac{\partial f}{\partial y} \end{bmatrix}\] 1. Gradient Magnitude: Measures edge strength at coordinate \((x, y)\): \[M(x, y) = \|\nabla f\| = \sqrt{G_x^2 + G_y^2} \approx |G_x| + |G_y|\] 2. Gradient Direction (Orientation Angle): Orthogonal to the edge contour direction: \[\theta(x, y) = \arctan\left(\frac{G_y}{G_x}\right)\]

B. Sobel Gradient Operators

The Sobel operator combines Gaussian smoothing with differential differentiation to provide noise resistance. It uses two orthogonal \(3 \times 3\) convolutional kernels:

\[S_x = \begin{bmatrix} -1 & 0 & +1 \\ -2 & 0 & +2 \\ -1 & 0 & +1 \end{bmatrix} \quad (\text{Horizontal Gradient } G_x, \text{ Detects Vertical Edges})\] \[S_y = \begin{bmatrix} -1 & -2 & -1 \\ 0 & 0 & 0 \\ +1 & +2 & +1 \end{bmatrix} \quad (\text{Vertical Gradient } G_y, \text{ Detects Horizontal Edges})\]

C. The 5-Stage Canny Edge Detection Pipeline

Developed by John F. Canny in 1986, the Canny edge detector is widely regarded as the optimal edge detector, satisfying three optimality criteria: low error rate, localized edge markers, and single-pixel response:

  • Stage 1: Gaussian Filtering: Convolve input image with a Gaussian kernel (\(5 \times 5\), \(\sigma = 1.4\)) to suppress high-frequency image sensor noise.
  • Stage 2: Gradient Intensity & Direction: Apply Sobel kernels \(S_x\) and \(S_y\) to compute gradient magnitude \(M(x, y)\) and quantize edge direction \(\theta\) into 4 discrete directions: horizontal (\(0^\circ\)), positive diagonal (\(45^\circ\)), vertical (\(90^\circ\)), and negative diagonal (\(135^\circ\)).
  • Stage 3: Non-Maximum Suppression (NMS): Thins wide gradient ridges into 1-pixel wide crisp edges. For each pixel, compare its magnitude \(M(x, y)\) against the two adjacent neighbors along its gradient direction \(\theta\). If \(M(x, y)\) is not strictly greater than both neighbors, suppress it to \(0\).
  • Stage 4: Double Thresholding: Classify remaining candidate pixels into three categories using two user-defined thresholds (\(T_{\text{High}}\) and \(T_{\text{Low}}\), typically ratio \(2:1\) or \(3:1\)):
    • Strong Edges: \(M(x, y) \ge T_{\text{High}}\) (retained unconditionally).
    • Weak Edges: \(T_{\text{Low}} \le M(x, y) < T_{\text{High}}\) (evaluated in Stage 5).
    • Non-Edges: \(M(x, y) < T_{\text{Low}}\) (permanently suppressed to 0).
  • Stage 5: Edge Tracking by Hysteresis: Weak edge pixels are preserved if and only if they are directly connected in an 8-connected neighborhood to at least one Strong edge pixel. Isolated weak edges caused by noise are eliminated.

✂️ Module 4: Image Segmentation, Otsu Binarization & Mathematical Morphology

Otsu Variance Optimization • Contour Hierarchy • Structuring Elements

🎯 Learning Objectives

  • Differentiate between Global, Adaptive, and Otsu's optimal thresholding.
  • Derive Otsu's Between-Class Variance objective function \(\sigma_b^2(T)\).
  • Trace morphological operators: Erosion, Dilation, Morphological Opening, and Morphological Closing.
  • Extract vector contours, calculate area, perimeter, and bounding boxes.

🌍 Real-World Applications

  • License plate character segmentation, barcode binarization under uneven lighting.
  • Blood cell microscopy counting, robotic vision gripper boundary localization.

A. Thresholding Techniques: Global vs. Adaptive vs. Otsu

Thresholding partitions a grayscale image into foreground objects and background based on pixel intensity:

  • Simple Global Thresholding: Uses a single constant scalar threshold \(T\) across the entire image: \(g(x, y) = 255 \text{ if } f(x, y) > T \text{ else } 0\). Fails catastrophically under non-uniform illumination or shadows.
  • Adaptive Thresholding: Calculates a localized threshold \(T(x, y)\) for each pixel dynamically based on the Gaussian-weighted or mean intensity of a local \(B \times B\) neighborhood minus a constant \(C\). Resilient to shadows and gradients.
  • Otsu's Thresholding (Nobuyuki Otsu, 1979): An unsupervised statistical algorithm that automatically selects the optimal global threshold \(T^*\) for bimodal histograms by maximizing the between-class variance \(\sigma_b^2(T)\):
\[T^* = \arg\max_{0 \le T < L} \sigma_b^2(T) = \arg\max_{0 \le T < L} \left[ \omega_0(T) \, \omega_1(T) \, (\mu_0(T) - \mu_1(T))^2 \right]\] Where \(\omega_0(T)\) and \(\omega_1(T)\) are the cumulative probabilities of background and foreground classes, and \(\mu_0(T)\) and \(\mu_1(T)\) are their respective mean intensities.

B. Mathematical Morphology & Structuring Elements

Mathematical morphology processes binary shapes based on set theory using a small geometric probe called a Structuring Element (Kernel \(B\)):

Operation Mathematical Set Definition Visual Effect on Binary Foreground Primary Practical Function
Erosion \(A \ominus B = \{z \mid (B)_z \subseteq A\}\) Shrinks foreground boundaries; strips outer layer of pixels. Eliminates tiny isolated white noise specks and disconnects thin bridges between objects.
Dilation \(A \oplus B = \{z \mid (\hat{B})_z \cap A \ne \emptyset\}\) Expands foreground boundaries; adds pixels to object perimeter. Bridges small gaps, connects broken character strokes, fills small internal dark voids.
Opening \(A \circ B = (A \ominus B) \oplus B\) Erosion followed by Dilation. Removes background noise and smooths outer contours while preserving original object dimensions.
Closing \(A \bullet B = (A \oplus B) \ominus B\) Dilation followed by Erosion. Fills small black holes inside foreground objects and connects adjacent segments without expanding outer shape.

🎯 Module 5: Object Detection, Feature Descriptors & Modern YOLO Architectures

Classification vs Detection • HOG & SIFT • Single-Shot Deep Detectors

🎯 Learning Objectives

  • Distinguish between Classification, Localization, Object Detection, and Instance Segmentation.
  • Understand classical feature descriptors: Histogram of Oriented Gradients (HOG) and SIFT.
  • Formulate Bounding Box coordinates, Intersection over Union (IoU), and Non-Maximum Suppression (NMS).
  • Contrast classical Haar Cascades with single-shot real-time deep neural networks (YOLO).

🌍 Real-World Applications

  • Pedestrian and vehicle collision avoidance in self-driving cars (Tesla Autopilot / Waymo).
  • Automated biometric facial unlocking, retail shelf inventory stock detection.

A. Computer Vision Task Hierarchy

  • Image Classification: Predicts a single categorical class label for the entire image (e.g., "Dog"). Answers What is in the image?
  • Object Localization: Predicts class label plus the bounding box coordinates \([x, y, w, h]\) of a single primary object. Answers What and Where is it?
  • Object Detection: Detects, classifies, and draws bounding boxes around multiple distinct object instances of varying classes in a single frame.
  • Instance Segmentation: Predicts a pixel-level binary mask for each individual detected object instance (e.g., Mask R-CNN).

B. Intersection over Union (IoU) Evaluation Metric

To evaluate the spatial accuracy of a predicted bounding box \(B_p\) against ground truth box \(B_{gt}\), computer vision uses Intersection over Union (Jaccard Index):

\[\text{IoU} = \frac{\text{Area}(B_p \cap B_{gt})}{\text{Area}(B_p \cup B_{gt})} = \frac{\text{Overlap Area}}{\text{Union Area}}\] A prediction is standardly considered a True Positive (TP) if \(\text{IoU} \ge 0.50\) (or \(\text{IoU} \ge 0.75\) in strict benchmarks).

C. Classical vs. Modern Deep Learning Detection Paradigms

Detection Paradigm Key Architecture / Method Inference Speed Feature Representation Mechanism
Classical: Haar Cascades Viola-Jones (2001) AdaBoost Cascade Ultra-Fast (CPU 60+ FPS) Handcrafted rectangular Haar-like features computed in \(O(1)\) time via Integral Images. Sensitive to orientation and lighting changes.
Classical: HOG + SVM Dalal & Triggs (2005) Moderate (10–25 FPS) Normalizes local gradient orientation histograms across spatial cell blocks. Standard baseline for pedestrian detection prior to deep learning.
Deep Learning: Two-Stage Faster R-CNN (Ren et al., 2015) Slower (5–15 FPS) Stage 1 proposes candidate regions via Region Proposal Network (RPN); Stage 2 extracts features via RoI Pooling and classifies candidates. High accuracy.
Deep Learning: Single-Stage YOLO (Redmon et al., 2016) / SSD Real-Time (45–140 FPS) Divides image into an \(S \times S\) grid. A single convolutional backbone predicts bounding boxes, confidence scores, and class probabilities simultaneously in one forward pass.

🔬 Module 6: OpenCV Practical Laboratory Manual (10 Curriculum Experiments)

Complete Runnable Python • Algorithms • Expected Outputs • Viva Questions

Experiment 1: Image Acquisition, Loading, and Display

Aim: Write a Python script using OpenCV to read an image from disk, inspect its dimensions and data type, and display it in the vision canvas.

import cv2

# Read image in default BGR mode
img = cv2.imread('/input.jpg')
if img is not None:
    height, width, channels = img.shape
    print(f"Image Resolution: {width}x{height} | Channels: {channels} | Dtype: {img.dtype}")
    cv2_imshow(img)
else:
    print("Error: Could not load image from filesystem.")

Experiment 2: RGB to Grayscale Conversion

Aim: Convert a 3-channel BGR color image to single-channel 8-bit grayscale using ITU-R BT.601 luminous weighting.

import cv2

img = cv2.imread('/input.jpg')
# Convert BGR color space to Grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print(f"Original shape: {img.shape} -> Grayscale shape: {gray.shape}")
cv2_imshow(gray)

Experiment 3: Gaussian Blur Smoothing & Noise Reduction

Aim: Apply a 2D Gaussian smoothing filter to suppress high-frequency image noise prior to edge detection.

import cv2

img = cv2.imread('/input.jpg')
# Gaussian Blur with 7x7 kernel and sigma = 1.5
blurred = cv2.GaussianBlur(img, (7, 7), sigmaX=1.5)
cv2_imshow(blurred)

Experiment 4: Binary Thresholding & Otsu Binarization

Aim: Segment foreground objects from background using automated Otsu variance thresholding.

import cv2

gray = cv2.cvtColor(cv2.imread('/input.jpg'), cv2.COLOR_BGR2GRAY)
# Automated Otsu binarization
optimal_thresh, binary_mask = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
print(f"Otsu Optimal Threshold calculated: {optimal_thresh:.1f}")
cv2_imshow(binary_mask)

Experiment 5: Canny Multi-Stage Edge Detection

Aim: Detect structural edge boundaries using the optimal 5-stage Canny algorithm with hysteresis thresholding.

import cv2

gray = cv2.cvtColor(cv2.imread('/input.jpg'), cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 1.2)
# Canny with Low Threshold = 50, High Threshold = 150
edges = cv2.Canny(blurred, threshold1=50, threshold2=150)
cv2_imshow(edges)

Experiment 6: Sobel Gradient Vector Field

Aim: Compute horizontal and vertical spatial derivatives using \(3 \times 3\) Sobel kernels.

import cv2
import numpy as np

gray = cv2.cvtColor(cv2.imread('/input.jpg'), cv2.COLOR_BGR2GRAY)
# 64-bit float gradients to capture negative slopes
sobel_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)
sobel_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)
# Combine gradient magnitudes
magnitude = cv2.magnitude(sobel_x, sobel_y)
sobel_combined = np.uint8(np.clip(magnitude, 0, 255))
cv2_imshow(sobel_combined)

Experiment 7: Contour Detection & Perimeter Analysis

Aim: Extract closed external contours from a binary image and calculate geometric properties.

import cv2

img = cv2.imread('/input.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print(f"Total Contours Detected: {len(contours)}")
# Draw detected contours in green
annotated = img.copy()
cv2.drawContours(annotated, contours, -1, (0, 255, 0), 2)
cv2_imshow(annotated)

Experiment 8: Morphological Erosion & Dilation

Aim: Demonstrate noise reduction and boundary expansion using structuring elements.

import cv2
import numpy as np

gray = cv2.cvtColor(cv2.imread('/input.jpg'), cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
kernel = np.ones((5, 5), np.uint8)
# Opening (Erosion followed by Dilation) to remove background specks
opened = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
cv2_imshow(opened)

Experiment 9: Geometric Affine Transformation (Rotate & Scale)

Aim: Rotate an image by 45 degrees around its geometric center using an affine transformation matrix.

import cv2

img = cv2.imread('/input.jpg')
h, w = img.shape[:2]
center = (w // 2, h // 2)
# Compute 2x3 rotation matrix for 45 degrees rotation, scaled by 1.0
rot_matrix = cv2.getRotationMatrix2D(center, angle=45, scale=1.0)
rotated = cv2.warpAffine(img, rot_matrix, (w, h))
cv2_imshow(rotated)

Experiment 10: Drawing Bounding Boxes & Visual Annotations

Aim: Programmatically compute bounding boxes for detected objects and draw labeled overlays.

import cv2

img = cv2.imread('/input.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

canvas = img.copy()
for cnt in contours:
    if cv2.contourArea(cnt) > 200:
        x, y, w, h = cv2.boundingRect(cnt)
        cv2.rectangle(canvas, (x, y), (x + w, y + h), (0, 165, 255), 2)
        cv2.putText(canvas, f"Object ({w}x{h})", (x, y - 8),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 165, 255), 1)

cv2_imshow(canvas)
Standard University Viva Voce Examination Questions:
• Q: Why does OpenCV load images in BGR format instead of RGB?
A: Early computer vision libraries and camera framegrabber manufacturers in the 1990s stored framebuffer pixels in little-endian order (Blue, Green, Red). OpenCV preserved BGR to maintain backward compatibility.
• Q: Why must Sobel gradient filters use 64-bit float (cv2.CV_64F) rather than 8-bit unsigned integer (uint8)?
A: Light transitions from black to white yield positive derivatives (\(+255\)), but white-to-black transitions yield negative derivatives (\(-255\)). If stored in uint8, all negative slopes are truncated to zero, causing half of all image edges to vanish. Gradients must be computed in signed floats before taking absolute magnitudes.
• Q: What is the primary operational advantage of the Canny detector over the Sobel filter?
A: Sobel produces thick, fuzzy gradient ridges that vary with threshold. Canny incorporates Non-Maximum Suppression (NMS) to thin all edges to exactly 1 pixel width, and hysteresis double thresholding to prevent edge fragmentation.

👁️ Experiment 4: Image Dilation

Standardized university Computer Vision & Digital Image Processing practical syllabus specification. Implemented in Python 3 using OpenCV (cv2) and NumPy.

📋 Curriculum Specifications & Core OpenCV Functions

Basic Operations • Practical Lab

Aim: Read an image in Python and Dilate an Image using Dilate function.

Primary OpenCV Functions Used

• cv2.dilate
• cv2.getStructuringElement
• cv2_imshow

Execution Environment

• Language: Python 3.11 with NumPy array backend.
• Libraries: cv2, numpy, matplotlib.pyplot.
• Color Matrix: BGR default representation in OpenCV.

Step-by-Step Algorithm

  1. Load input digital image into memory using cv2.imread() as a NumPy multi-dimensional array.
  2. Validate that the image is loaded successfully and inspect its dimensional shape (height, width, color channels).
  3. Apply image transformation / processing filter: cv2.dilate.
  4. Inspect and compute modified pixel matrix values or bounding coordinate arrays.
  5. Render original vs processed output images side-by-side using cv2.imshow() or inline canvas rendering.

Complete Runnable Source Code

import cv2

from google.colab import files
from google.colab.patches import cv2_imshow

f = files.upload()

img = cv2.imread(list(f.keys())[0])

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))

dilate = cv2.dilate(gray, kernel)

cv2_imshow(img)
cv2_imshow(dilate)
Viva Voce Oral Exam Preparation:
• Q: Why does OpenCV store images in BGR format rather than standard RGB?
• Answer: When OpenCV was initially developed by Intel in 1999, the BGR color representation was the standard format used by camera software drivers and Microsoft Windows DIB (Device Independent Bitmap) specifications. OpenCV maintained BGR for backwards compatibility.

• Q: What is the underlying data structure of an OpenCV image in Python?
• Answer: An OpenCV image in Python is stored directly as a contiguous n-dimensional numpy.ndarray of 8-bit unsigned integers (dtype=uint8), with pixel intensities ranging from 0 to 255.