You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A comprehensive collection of practical laboratory experiments, benchmarks, and assignments for Introduction to Computer Vision (7th Semester). This repository explores classical image processing pipelines, spatial filtering, edge detection, mathematical morphology, deep Convolutional Neural Networks (CNNs) benchmarked on dermoscopic medical imaging datasets (ISIC and HAM10000), feature-descriptor-based industrial defect detection pipelines (HOG + Kernel SVM) with real-time web deployment, scale-invariant feature transform (SIFT) landmark recognition with RANSAC homography localization and open-set rejection, evolutionary feature selection using Genetic Algorithms (GA-HOG) for medical image classification (PneumoniaMNIST), a comparative study of classical gradient and keypoint feature representations (HOG vs. Dense SIFT with Linear SVM) alongside perturbation robustness stress testing on microscopic blood-cell images (BloodMNIST) for the Midterm Lab Examination, a region-aware bone fracture detection and localization framework using deep YOLO object detection on the FracAtlas musculoskeletal radiograph benchmark (CV Lab 09: FractureVision), an empirical benchmarking study of six fundamental machine learning regression algorithms across linear, ensemble, nearest-neighbor, and deep neural paradigms (Lab Assignment 02 / Lab 10), and an in-depth investigation of Convolutional Neural Network (CNN) layer mechanics, feature-map activation dynamics, manual vs. framework parameter audits, receptive field scaling, and gradient symmetry breaking (CV Lab 12).
Analysis: Feature extraction, downstream classifiers (Softmax, SVM, Random Forest) on deep embeddings, FLOPs/parameter counts, inference latency, and convergence characteristics.
Lab 02: Spatial Filtering & Feature Enhancement
Objective: Quantify the exact impact of spatial filtering and preprocessing transformations on downstream deep learning classification performance.
Experimental Design: 18 controlled training runs (3 backbone models $\times$ 6 filter variations) with identical splits, random seeds, and hyperparameters:
Objective: Evaluate classical first-order, second-order, and multi-stage edge operators under clean and corrupted environments, and examine their utility as direct input representations for neural networks.
Algorithms Analyzed:
Sobel & Prewitt (1st-order gradient operators with directional smoothing)
Laplacian & Laplacian of Gaussian (LoG) (2nd-order zero-crossing isotropic operators)
Gradient vs. Multi-stage boundary extraction (Sobel vs. Canny with threshold pairs: 50/100, 100/200, 150/250)
Mathematical morphology (dilation, closing to bridge fragmented boundaries)
Contour extraction and shape morphometrics: Lesion Area, Perimeter, and Circularity / Compactness
Analysis: In-depth evaluation of dermoscopy artifacts (hair occlusions, faint boundaries, low contrast) and clinical trade-offs between operator sensitivity and specificity.
Lab 05: Industrial Defect Detection using HOG & Kernel SVM
Objective: Detect manufacturing surface defects on steel sheets (hot-rolled plates) using Histogram of Oriented Gradients (HOG) feature extraction and machine learning classifiers.
Key Components & Experiments:
HOG Parameter Optimization: Systematic parameter sweep evaluating cell sizes ($4\times4$, $8\times8$, $16\times16$), orientations ($6, 9, 12$), and block sizes ($1\times1$, $2\times2$, $3\times3$) with L2-Hys normalization. The optimal configuration ($8\times8$ cells, 9 bins, $2\times2$ blocks, $128\times128$ window) yields an 8,100-dimensional descriptor.
Classifier Benchmarking: Comparative analysis of Kernel SVM (RBF), Linear SVM, Random Forest, k-NN, and XGBoost. Kernel SVM achieved top performance with 77.74% Accuracy and 81.95% F1-Score in binary defect classification, and 83.89% Macro-Accuracy in multi-class defect categorization across 6 classes (Crazing, Inclusion, Patches, Pitted Surface, Rolled-in Scale, Scratches).
Sliding-Window Industrial Decision Module: Full-image surface scanning with $64\times64$ windows (stride 32px), local patch classification, and thresholded spatial anomaly aggregation to automate ACCEPT (PASS) or REJECT (DEFECTIVE) decisions.
Robustness & Perturbation Analysis: Stress testing under synthetic noise, contrast shifts, and spatial rotations to evaluate descriptor stability under production floor lighting variations.
Bonus Challenge Prototype (Real-Time Deployment):
Interactive Flask web application simulating industrial quality control.
Single & Batch Image Inspection: Upload or select sample steel plates with automatic bounding box localization around detected defect patches.
Video Stream Inspection: Frame-by-frame analysis of simulated conveyor belt footage with defect rate counters and rejection logs.
Live Webcam Inspection: Real-time $200\times200$ ROI video stream extraction displaying dynamic PASS/DEFECTIVE status and confidence scoring.
Lab 06: Landmark Recognition & Localization using SIFT & RANSAC
Objective: Construct a feature-based landmark recognition and geometric localization system using Scale-Invariant Feature Transform (SIFT) and RANSAC Homography, featuring strict open-set rejection for unseen queries.
Reference Gallery & Dataset:
Curated database of 6 global landmarks from Kaggle's Wonders of the World dataset: Taj Mahal, Great Wall of China, Statue of Liberty, Roman Colosseum, Pyramids of Giza, Christ the Redeemer.
Reference gallery composed of 8 distinct viewpoints per landmark (48 reference images total), multithreaded SIFT feature extraction (up to 2,000 features per image), downscaled to max dimension 800 px.
Matching & Localization Pipeline:
Feature Extraction: Grayscale conversion and keypoint/128-dimensional descriptor extraction via cv2.SIFT_create(nfeatures=2000).
Key Finding: SIFT proved robust to rotation (13.8 avg matches, 7.8 inliers), but sensitive to extreme resolution reduction and low illumination. The multi-stage inlier and margin gating completely eliminated false recognitions (0% false acceptance on open-set queries).
Lab 07: Evolutionary Feature Selection for Medical Image Classification (GA-HOG)
Objective: Modify the classical Histogram of Oriented Gradients (HOG) pipeline by incorporating a Genetic Algorithm (GA) wrapper for feature selection to reduce descriptor dimensionality and boost classification on medical imaging.
Dataset:PneumoniaMNIST from MedMNIST v2 (pediatric chest X-ray binary classification: Normal vs. Pneumonia; 5,030 total images with fixed splits: 3,882 train / 524 validation / 624 test).
Pipeline & Architecture:
Feature Extraction: Standard HOG descriptor ($128\times128$ resolution, 9 orientations, $8\times8$ pixel cells, $2\times2$ cell blocks, L2-Hys normalization) yielding 8,100 features per image.
GA Optimization Wrapper: Searches a binary feature selection mask over 8,100 dimensions. Fitness balances validation macro-F1 against feature sparsity: $\text{Fitness} = \text{Macro-F1}_{\text{val}} - 0.05 \times \frac{|\text{selected features}|}{8,100}$.
Genetic Operators: Tournament selection (size 3), uniform crossover ($p = 0.9$), bit-flip mutation, and elitism (2 best individuals preserved) evolved over 15 generations.
GPU-Accelerated Kernel SVM: Fast RBF kernel Gram matrices evaluated on GPU (PyTorch) with scikit-learn precomputed SVC(kernel="precomputed"), exploring three GA configurations (GA-A, GA-B, GA-C).
Key Findings:
The optimal configuration (GA-A) reduced feature dimensionality by 73.7% (retaining only 2,129 out of 8,100 features).
Outperformed standard baseline HOG on the unseen test set across all primary metrics: Macro-F1 +4.58% (77.36% $\to$81.95%), Accuracy +3.21% (81.57% $\to$84.78%), and Normal class recall +8.98% (51.28% $\to$60.26%).
CV Lab Mid: HOG vs. SIFT on Blood-Cell Images (BloodMNIST)
Objective: Systematically compare and analyze classical gradient-based (HOG) and keypoint-based (Dense SIFT) feature representation pipelines paired with Linear Support Vector Machines (LinearSVC) on microscopic blood-cell classification.
Dataset:BloodMNIST (MedMNIST v2) 4-class balanced subset: eosinophil (ID 1), monocyte (ID 5), neutrophil (ID 6), and platelet (ID 7) standardized to $128\times128$ grayscale (400 train, 120 validation, 120 test).
Pipelines & Feature Representations:
HOG + Linear SVM: Configured with cell size $16\times16$, $2\times2$ blocks (stride 1 cell), 9 orientation bins, and L2-Hys block normalization $\to$1,764 features per image. Hyperparameter grid sweep on validation set ($C \in {0.1, 1, 10}$) selected $C=0.1$$\to$78.33% Val Accuracy, 78.27% Macro-F1.
Dense SIFT + Linear SVM: Keypoints sampled at uniform regular $4\times4$ grid coordinates (16 keypoints total, diameter 32px, fixed orientation $\theta=0^\circ$), generating concatenated 128-dimensional descriptors $\to$2,048 features per image. Hyperparameter grid sweep on validation set selected $C=0.1$$\to$75.00% Val Accuracy, 75.23% Macro-F1.
Robustness & Perturbation Stress Testing:
Evaluated on completely unseen test data across three conditions: Clean, Rotated 20° (in-plane affine transformation), and Additive Gaussian Noise ($\sigma = 0.05$).
Rotation: HOG exhibited higher rotational stability (-5.83 pp drop: 72.50% $\to$ 66.67%) than dense fixed-grid SIFT (-33.34 pp drop: 79.17% $\to$ 45.83%) because fixed-angle SIFT without dominant orientation assignment is non-rotation-invariant.
Additive Noise: Dense SIFT showed remarkable noise resistance (+2.50 pp: 79.17% $\to$ 81.67%) due to Gaussian spatial weighting averaging over 32px neighborhoods, whereas HOG collapsed (-47.50 pp drop: 72.50% $\to$ 25.00%) due to un-smoothed 1st-order pixel gradients amplifying high-frequency noise.
Error Analysis & Granulocyte Confusion:
Eosinophils exhibited the highest confusion across both pipelines (eosinophil$\leftrightarrow$monocyte in HOG, eosinophil$\leftrightarrow$neutrophil in SIFT). This stems from converting to grayscale, which strips essential cytoplasmic granule staining coloration (e.g., distinctive eosinophilic red-orange granule tint).
CV Lab 09: FractureVision - Region-Aware Bone Fracture Detection using YOLO
Objective: Formulate, design, and simulate a region-aware deep learning framework (FractureVision) to detect and localize suspicious bone fracture regions in musculoskeletal X-ray radiographs, modeling its integration into an orthopedic clinical assistance workflow.
Dataset:FracAtlas benchmark dataset (4,083 musculoskeletal radiographs across hand, leg, hip, and shoulder collected from 3 hospitals in Bangladesh, containing 717 verified fractured scans and 922 annotated fracture instances with expert consensus).
Target Anatomical Regions:
Hand: 1,538 scans (437 fractured), characterized by intricate clusters of small overlapping bones, high occlusion, and subtle micro-fractures near phalanges and metacarpals.
Hand and leg account for over 97% of fractured images in FracAtlas, providing substantial structural diversity and training stability compared to under-represented regions (hip and shoulder with only 63 fractures each).
Model Architecture & Workflow:
YOLO Single-Stage Detection: Fast bounding box regression and objectness scoring trained with a single detection class (fracture).
User-Guided Region Awareness: Two-stage clinical interaction where the user specifies the target anatomical structure (Hand or Leg) before uploading the radiograph, routing inference appropriately.
AI-Assisted Workflow Simulation: Returns localized bounding boxes with confidence scores to direct clinician attention toward subtle or ambiguous fractures without replacing professional clinical judgment.
Lab Assignment 02 (Lab 10): Comparative Implementation of ML Regression Algorithms
Objective: Mathematically formulate, trace manual step-by-step calculations on sample micro-subsets, and empirically benchmark six classical and modern machine learning regression paradigms on continuous salary estimation.
Algorithms Analyzed:
Linear Regression: Ordinary Least Squares (OLS) closed-form normal equations ($\mathbf{w} = (\mathbf{X}^T\mathbf{X})^{-1}\mathbf{X}^Ty$) and gradient formulations with feature standardization.
Decision Tree Regression: CART algorithm recursively finding binary split thresholds that maximize MSE impurity reduction; leaf values evaluated as local target means.
Random Forest Regression: Bagging ensemble of 300 de-correlated decision trees (max depth 3, min samples leaf 1) with bootstrap aggregation.
Neural Network (MLP): PyTorch deep neural regressor ($1 \to 64 \to 32 \to 1$ architecture with ReLU activations, Adam optimizer with weight decay, cosine annealing learning rate scheduler over 1,500 epochs trained on CUDA GPU).
XGBoost: Gradient boosted decision trees using second-order Taylor expansion approximations (exact gradient $g_i$ and Hessian $h_i$ formulations) trained on CUDA GPU.
Strict 80:20 train/test split (24 training samples, 6 test samples, random_state = 42).
Strict zero data leakage: feature scaling fit strictly on training splits.
Hyperparameter optimization via 5-fold cross-validation grid search (GridSearchCV) on training data.
Manual step-by-step mathematical calculations and traces worked out by hand for each algorithm.
Key Findings:
Linear Regression Ranked #1 on Test Set: Achieved lowest MAE (6,286.45), lowest MSE ($49.83 \times 10^6$), lowest RMSE (7,059.04), and highest $R^2$ (0.9024). Because the true underlying relationship between experience and salary is strongly linear ($r = 0.9782$), low-variance linear models excel on small datasets without risk of overfitting.
Tree Discretization vs. Smooth Curves: Decision trees and tree-ensembles partition continuous 1D space into orthogonal step functions, causing higher boundary error and inability to extrapolate beyond training ranges.
5-Fold Cross-Validation Consensus: Random Forest scored lowest average CV RMSE (5,327.41, CV $R^2 = 0.9262$) closely followed by Linear Regression (5,694.82, CV $R^2 = 0.9224$), confirming both models perform exceptionally well within noise margins.
Objective: Dissect the internal operational mechanics of Convolutional Neural Networks by visualizing spatial filter transformations across a $5\times4$ feature-map grid, rigorously auditing layer parameters by hand against PyTorch framework counts, evaluating receptive field scaling efficiency, and investigating layer commutativity and gradient symmetry breaking.
Part I: Spatial Filtering & Activation Pipeline:
Filter Suite ($3\times3$ Kernels): Horizontal Edge (Sobel), Vertical Edge (Sobel), Sharpening, Gaussian Blur, and Emboss kernels applied to a synthetic $256\times256$ building facade.
Feature Map Dynamics: Analyzed tensor transformations across 4 stages: Raw Convolution ($5\times256\times256$) $\to$ ReLU Activation ($5\times256\times256$) $\to$ Max Pooling ($5\times128\times128$, $2\times2$, stride 2) vs. Average Pooling ($5\times128\times128$, $2\times2$, stride 2).
Empirical Behavior: Edge filters generated over 50% negative values ($50.2%$ horizontal, $54.9%$ vertical) entirely zeroed out by ReLU. Max pooling preserved sharp structural peaks (retaining 100% of maximum filter responses), while average pooling suppressed peak intensity by approximately $50%$ on sparse edge maps.
Non-Linearity & Background Inversion: Contrasted ReLU, Leaky ReLU ($\alpha=0.1$), and Sigmoid behaviors. Demonstrated on dark ink text on white backgrounds that standard max pooling erodes thin dark features ($1,822 \to 285$ surviving ink pixels) because ink is represented by minimum pixel intensities, whereas average pooling preserves significantly more signal (542 pixels).
Part II: Mathematical Parameter Audit & Framework Verification:
Validated via automated assertions matching PyTorch framework model definitions and torchinfo summaries.
Part III: Layer Mechanics, Receptive Fields & Symmetry Breaking:
Receptive Field Efficiency: Proved that two cascaded $3\times3$ convolutions achieve the exact same $5\times5$ spatial receptive field as a single $5\times5$ convolution while reducing parameters by $27.0%\text{ to }27.9%$ and adding intermediate non-linear representations.
Layer Commutativity: Proved and empirically verified across GPU tensors that $\text{ReLU}(\text{MaxPool}(X)) \equiv \text{MaxPool}(\text{ReLU}(X))$ (reducing ReLU FLOPs by $4\times$ when pooling is computed first). Demonstrated that Average Pooling does not commute with ReLU.
Filter Collapse & Symmetry Breaking: Demonstrated that identical filter weight initialization causes identical gradient updates, collapsing all filters into redundancy (mean pairwise cosine similarity of $1.000$, loss plateaus at $0.693$), whereas Kaiming/He random initialization breaks symmetry, fostering diverse, decorrelated feature representations (cosine similarity $-0.152$, loss drops to $0.651$).