Skip to content

About

Laboratory experiments, assignments, and benchmarks for Computer Vision: spatial filtering, edge detection, deep CNNs, HOG + SVM defect detection, SIFT matching, GA-HOG, BloodMNIST, YOLO fracture detection, ML regression, and CNN layer visualization.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Computer Vision Labs & Assignments

License: MIT Python PyTorch OpenCV Jupyter

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).


📑 Table of Contents


📂 Repository Structure

Computer-Vision-Labs/
├── CV Lab 01/
│   ├── CV_LAB_01.ipynb             # Deep CNN architectures benchmarking
│   └── FA23-BAI-013.docx           # Lab report and documentation
│
├── CV Lab 02/
│   ├── CV_LAB_02.ipynb             # Image filtering impact on CNN classification
│   ├── Lab02.md                    # Detailed results, metrics, and discussion
│   └── lab02_results/              # Metric tables, confusion matrices, filter response curves
│
├── CV Lab 03/
│   ├── CV_LAB_03.ipynb             # Comprehensive edge detection and noise robustness
│   ├── Lab-03.md                   # Metric tables and theoretical discussion
│   ├── Report.pdf                  # Complete formal academic lab report
│   └── lab3_results/               # Plots, confusion matrices, and benchmark tables
│
├── Lab Assignment 01_CV Lab 04/
│   ├── Skin_Lesion_Boundary_Detection.ipynb   # Boundary extraction & morphology
│   ├── Skin_Lesion_Boundary_Detection.md      # Quantitative morphometrics & answers
│   └── skin_lesion_results/                   # Visualizations and area/perimeter logs
│
├── CV Lab 05/
│   ├── HOG_Defect_Detection.ipynb  # End-to-end HOG pipeline, sweeps & classifier benchmarks
│   ├── Lab_Report.docx             # Formal academic lab report and analysis
│   ├── Outputs/                    # Heatmaps, confusion matrices, and CSV evaluation benchmarks
│   └── Bonus Task/                 # Real-time HOG industrial quality inspection prototype (Flask web app)
│       ├── app.py                  # Flask inspection server with webcam, video & image routes
│       ├── predictor.py            # Sliding window HOG inference & bounding box visualizer
│       ├── hog_utils.py            # HOG feature descriptor extraction & visualization helpers
│       ├── hog_defect_model.joblib # Pre-trained Kernel SVM (RBF) industrial defect model
│       ├── templates/ & static/    # Modern dark-mode UI with real-time inspection indicators
│       ├── sample_images/          # Normal & defective steel samples and conveyor belt test video
│       └── requirements.txt        # Bonus app dependencies
│
├── CV Lab 06/
│   ├── SIFT_Landmark_Recognition.ipynb # End-to-end SIFT landmark recognition & homography pipeline
│   ├── Lab_Report.docx                 # Formal academic lab report and analysis
│   ├── Lab_Report.md                   # Complete Markdown report, metrics, and screenshots
│   ├── landmark_database/              # Reference gallery across 6 world landmarks (8 views each)
│   └── submission_files/               # Visualizations, test condition outputs, and experimental CSV
│
├── CV Lab 07/
│   ├── Lab07.ipynb                     # Executed GA-HOG feature selection & SVM training pipeline
│   ├── Lab 07.docx                     # Formal academic lab report documentation
│   ├── Lab07_Report.md                 # Complete Markdown report, metrics, and discussion
│   └── lab07_outputs/                  # Confusion matrices, feature distributions, GA fitness curves & CSVs
│
├── CV Lab Mid/
│   ├── FA23_BAI_013_Muhammad_Umer_Rafiq_LabMid.ipynb # Executed HOG vs. SIFT comparison, parameter sweeps & robustness evaluation
│   ├── LabMid Report.pdf                             # Formal academic midterm examination report
│   └── LabMid.md                                     # Full Markdown report, questions, results, confusion matrices & analysis
│
├── CV Lab 09/
│   ├── FractureVision Abstract & Intro.docx          # Academic research paper draft & project proposal
│   └── README.md                                     # Markdown documentation, abstract, workflow, and references
│
├── Lab Assignment 02_CV Lab 10/
│   ├── Regression Algorithms Comparison.ipynb        # Complete implementation, EDA, GPU training, and comparisons
│   ├── Lab_Assignment_02_Report.docx                 # Formal academic lab report documentation
│   └── Lab_Assignment_02_Report.md                   # Full report with theoretical derivations, manual hand traces & benchmarks
│
├── CV Lab 12/
│   ├── CNN_Visualization_Lab.ipynb                   # End-to-end PyTorch filter pipelines, feature-map grids, parameter audits & symmetry tests
│   └── CNN_Lab_Results.md                            # Quantitative metric tables, mathematical derivations, viva evidence & layer comparisons
│
├── LICENSE                             # MIT License
└── README.md                           # Repository documentation

🔬 Lab Overview & Modules

Lab 01: Deep CNN Architecture Benchmarking

  • Objective: Systematically evaluate and compare deep neural network vision backbones on dermoscopic skin lesion classification.
  • Architectures Evaluated:
    • Classic Deep Models: AlexNet, VGG16, VGG19
    • Residual Networks: ResNet18, ResNet50, ResNet101
    • Dense & Efficient Networks: DenseNet121, EfficientNet-B0
  • 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.
  • Dataset: 4-class ISIC subset (Basal Cell Carcinoma, Melanoma, Nevus, Pigmented Benign Keratosis).
  • Experimental Design: 18 controlled training runs (3 backbone models $\times$ 6 filter variations) with identical splits, random seeds, and hyperparameters:
    • No Filter (Baseline)
    • Average Blur ($3\times3$ box filter)
    • Gaussian Blur ($5\times5$, $\sigma = 1.0$)
    • Median Filter ($3\times3$)
    • Custom Sharpening Kernel ($\begin{bmatrix} 0 & -1 & 0 \ -1 & 5 & -1 \ 0 & -1 & 0 \end{bmatrix}$)
    • Sobel Gradient Magnitude ($3\times3$ Sobel $x + y$)
  • Key Takeaway: Custom high-pass sharpening on ResNet50 yielded top classification performance (71.88% Accuracy, 66.17% Macro-F1, 94.76% AUC), enhancing micro-texture and pigment networks.

Lab 03: Edge Detection, Noise Sensitivity & Edge Representations

  • 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)
    • Canny Edge Detector (Gaussian smoothing, gradient magnitude/direction, Non-Maximum Suppression, Hysteresis thresholding)
  • Controlled Noise Experiments:
    • Gaussian Noise ($\sigma = 25$) vs. Salt-and-Pepper Noise ($p = 0.05$).
    • Preprocessing restoration: Median filtering recovers up to +0.46 F1 against impulse noise; Gaussian filtering mitigates gradient noise variance.
  • Representation Study: Comparing classification models trained purely on raw RGB vs. edge maps vs. filtered inputs.

Lab Assignment 01 (Lab 04): Skin Lesion Boundary Detection & Morphometry

  • Objective: Design an end-to-end computer vision pipeline for automated lesion boundary extraction, artifact handling, and quantitative morphometric feature calculation.
  • Dataset: HAM10000 (kmader/skin-cancer-mnist-ham10000) across all 7 diagnostic categories (nv, mel, bkl, bcc, akiec, vasc, df).
  • Key Techniques:
    • Spatial pre-filtering (Gaussian, Median, Box blur)
    • 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).
    • Descriptor Matching: Brute-force Euclidean distance matching (cv2.BFMatcher(cv2.NORM_L2)) with $k=2$ nearest neighbors.
    • Ambiguity Filtering: Lowe's ratio test ($d_1 / d_2 < 0.75$) to discard non-distinctive repetitive matches.
    • Geometric Verification & Localization: Multi-point homography estimation (cv2.findHomography) with RANSAC reprojection error threshold ($\le 5.0$ px); projected bounding polygon validation ensuring convexity and plausible scene area ($0.01 \times A_{\text{query}} < A_{\text{poly}} < 3.0 \times A_{\text{query}}$).
    • Dual-Threshold Decision Rule: Multi-level acceptance criterion requiring $\ge 20$ reliable matches, $\ge 12$ RANSAC inliers, convex geometry, and a distinct inlier margin ($\ge 1.3\times$ over the runner-up landmark).
  • Stress Testing & Perturbation Analysis:
    • Evaluated across 32 query configurations: unaltered held-out images, 45° boundary-preserving rotations, 50% spatial downscaling, low illumination ($\alpha = 0.35$), viewpoint disparities, and negative/unseen landmarks (Stonehenge).
    • 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.
    • Leg: 2,272 scans (263 fractured), characterized by elongated structural shafts (tibia, fibula, femur) providing distinct morphological contrast.
    • 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.
    • K-Nearest Neighbors (KNN): Non-parametric instance-based regression ($k=6$, Euclidean distance, inverse distance weighting) on standardized feature spaces.
  • Experimental Design & Rigor:
    • 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.

CV Lab 12: CNN Visualization, Parameter Audit & Layer Mechanics

  • 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:
    • Designed standard CNN architectures ($32\times32\times3 \to \text{Conv1}(5) \to \text{ReLU} \to \text{Pool} \to \text{Conv2}(10) \to \text{ReLU} \to \text{Pool} \to \text{GAP} \to \text{Dense}(10)$).
    • Model A ($3\times3$ Kernels, Max Pooling): Derived closed-form parameter formula: $$\text{Conv1} = (3 \times 3 \times 3 + 1) \times 5 = 140, \quad \text{Conv2} = (3 \times 3 \times 5 + 1) \times 10 = 460, \quad \text{Dense} = (10 + 1) \times 10 = 110 \implies \mathbf{710\text{ params}}$$
    • Model B ($5\times5$ Kernels, Avg Pooling): $$\text{Conv1} = (5 \times 5 \times 3 + 1) \times 5 = 380, \quad \text{Conv2} = (5 \times 5 \times 5 + 1) \times 10 = 1,260, \quad \text{Dense} = 110 \implies \mathbf{1,750\text{ params}}$$
    • 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$).

📊 Key Empirical Results

Filter Benchmark Summary (Lab 02 — Test Set)

Backbone Architecture Filter Applied Accuracy (%) Precision (%) Recall (%) Macro-F1 (%) AUC (%)
ResNet50 Sharpening 71.88 79.96 71.88 66.17 94.76
ResNet50 Average Blur 68.75 76.93 68.75 64.84 87.60
ResNet50 Gaussian Blur 67.19 75.63 67.19 61.86 89.84
ResNet50 Baseline (Raw) 67.19 78.01 67.19 60.47 92.94
ResNet101 Average Blur 70.31 79.64 70.31 63.05 88.15
ResNet101 Sharpening 68.75 79.59 68.75 61.98 91.96
AlexNet Baseline (Raw) 67.19 73.20 67.19 64.85 90.20

Classifier Benchmark Summary (Lab 05 — Industrial Defect Detection)

Model Accuracy (%) Precision (%) Recall (%) F1-Score (%) Latency (ms/sample)
HOG + SVM (RBF) 77.74 80.43 83.52 81.95 0.14 ms
HOG + XGBoost (GPU) 76.39 79.71 81.78 80.73 0.12 ms
HOG + Random Forest 75.79 75.85 87.98 81.47 0.24 ms
HOG + SVM (Linear) 71.06 77.95 72.74 75.26 0.13 ms
HOG + kNN ($k=5$) 51.57 90.05 22.43 35.91 1.07 ms

SIFT Landmark Recognition Summary (Lab 06 — Test Perturbations & Open-Set Queries)

Query Condition Test Count Avg Keypoints Avg Reliable Matches Avg RANSAC Inliers Avg Inference Time (s) Recognition / Correct Rate
Rotated (45°) 6 347 13.8 7.8 0.58 s 1/6 (Recognized)
Different Viewpoint 6 670 15.5 8.7 0.93 s 0/6 (Rejected - Strict Margins)
Original (Held-out) 6 257 10.5 5.2 0.36 s 0/6 (Rejected - Below Threshold)
Resized (50% Scale) 6 90 5.0 0.0 0.12 s 0/6 (Rejected - Few Features)
Low Brightness ($\alpha=0.35$) 6 84 4.7 0.0 0.11 s 0/6 (Rejected - Low Contrast)
Open-Set Negative (Stonehenge) 2 948 31.0 6.5 1.82 s 2/2 (Correctly Rejected - 100%)
Overall Stress Benchmark 32 331 11.2 4.5 0.51 s 3/32 (9.4% strictly passed; 0% false positives)

GA-HOG Feature Selection Benchmark (Lab 07 — PneumoniaMNIST)

Pipeline Feature Dimension Reduction (%) Accuracy (%) Macro-Precision (%) Macro-Recall (%) Macro-F1 (%) Normal Recall (%) Pneumonia Recall (%)
GA-HOG + SVM (Proposed) 2,129 73.7% 84.78 89.63 79.87 81.95 60.26 99.49
HOG + SVM (Baseline) 8,100 0.0% 81.57 88.25 75.51 77.36 51.28 99.74
Net Improvement -5,971 features -73.7% +3.21% +1.38% +4.36% +4.58% +8.98% -0.25%

HOG vs. SIFT Robustness Benchmark (CV Lab Mid — BloodMNIST)

Pipeline / Representation Feature Dimension Validation Accuracy (%) Validation Macro-F1 (%) Test Clean Acc (%) Test Rotated (20°) Acc (%) Rotation Drop (pp) Test Noisy ($\sigma=0.05$) Acc (%) Noise Drop (pp)
HOG + Linear SVM 1,764 78.33 78.27 72.50 66.67 -5.83 25.00 -47.50
Dense SIFT + Linear SVM 2,048 75.00 75.23 79.17 45.83 -33.34 81.67 +2.50

Regression Benchmark Summary (Lab Assignment 02 / Lab 10)

Rank Regression Algorithm Optimal Parameters / Architecture Test MAE Test MSE Test RMSE Test $R^2$ 5-Fold CV RMSE 5-Fold CV $R^2$
1 Linear Regression OLS + StandardScaler 6,286.45 49,830,097 7,059.04 0.9024 5,694.82 0.9224
2 Random Forest $n=300$, max depth $=3$, min leaf $=1$ 6,563.44 59,801,030 7,733.11 0.8829 5,327.41 0.9262
3 Neural Network (MLP) $1 \to 64 \to 32 \to 1$, ReLU, Adam (GPU) 6,662.58 61,383,084 7,834.74 0.8798 6,928.47 0.8985
4 K-Nearest Neighbors (KNN) $k=6$, weights $=$ distance 6,905.99 65,979,671 8,122.79 0.8708 6,013.87 0.9062
5 XGBoost $n=100$, max depth $=2$, $\eta=0.05$ (GPU) 7,976.01 94,891,072 9,741.20 0.8142 6,490.49 0.8910
6 Decision Tree CART, max depth $=$ None, min leaf $=1$ 8,640.17 101,047,710 10,052.25 0.8022 6,822.62 0.8779

CNN Filter & Parameter Audit Summary (CV Lab 12)

1. Filter Response & Pooling Dynamics Statistics

Filter Kernel (3×3) min(A) max(A) % Pixels < 0 (Raw Conv A) % Zeros after ReLU (B) Mean MaxPool (C) Mean AvgPool (D) Peak MaxPool (C) Peak AvgPool (D) Peak Retention (Avg/Max)
Horizontal Edge (Sobel) -3.706 3.688 50.25% 50.25% 0.187 0.090 3.688 1.843 0.500
Vertical Edge (Sobel) -3.000 3.739 54.89% 54.89% 0.186 0.089 3.739 1.883 0.504
Sharpen -1.117 2.776 6.70% 6.70% 0.641 0.539 2.776 1.848 0.666
Gaussian Blur 0.103 0.930 0.00% 0.00% 0.528 0.507 0.930 0.929 0.999
Emboss -2.298 4.607 7.81% 7.81% 0.769 0.571 4.607 3.210 0.697

2. Architecture Parameter Audit & Receptive Field Scaling

Model Configuration Convolution Stages Kernel Size Pooling Scheme Theoretical Parameters PyTorch Framework Count Status
Model A (Standard) Conv1: 5, Conv2: 10 $3 \times 3$ Max Pooling ($2\times2$, s2) 710 710 Exact Match (Verified)
Model B (Large Kernel) Conv1: 5, Conv2: 10 $5 \times 5$ Avg Pooling ($2\times2$, s2) 1,750 1,750 Exact Match (Verified)

3. Symmetry Breaking & Filter Collapse Evaluation

Filter Weight Initialization Final Binary Cross-Entropy Loss Mean Pairwise Filter Cosine Similarity Filter Representation Diversity
Identical Initialization 0.693 1.000 Collapsed (Symmetry Trapped)
Kaiming / He Random Initialization 0.651 -0.152 Diverse & Disentangled

🛠️ Tech Stack & Dependencies

The experiments in this repository utilize standard scientific Python libraries, machine learning algorithms, and deep learning frameworks:

  • Language: Python 3.10+
  • Deep Learning: PyTorch, Torchvision
  • Computer Vision & Image Processing: OpenCV (cv2), scikit-image, Albumentations, PIL
  • Machine Learning & Evaluation: scikit-learn, XGBoost, Joblib
  • Data & Visualization: NumPy, Pandas, Matplotlib, Seaborn
  • Web Prototype (Bonus): Flask, HTML5, Vanilla CSS, JavaScript
  • Environment: Jupyter Notebook / Google Colab

🚀 Getting Started

1. Clone the Repository

git clone https://github.com/muhammadumerrafiq/Computer-Vision-Labs.git
cd Computer-Vision-Labs

2. Git LFS Setup (Download Model Weights)

This repository uses Git LFS for the large model file (hog_defect_model.joblib, ~183 MB) in Lab 05. Run:

git lfs install
git lfs pull

This is required so the actual hog_defect_model.joblib model binary is downloaded instead of only the Git LFS pointer.

3. Set Up a Virtual Environment

# Windows (PowerShell)
python -m venv venv
.\venv\Scripts\Activate.ps1

# Linux / macOS
python3 -m venv venv
source venv/bin/activate

4. Install Dependencies

pip install torch torchvision opencv-python numpy pandas matplotlib seaborn scikit-learn scikit-image xgboost joblib flask jupyter

5. Launch Jupyter Notebooks

jupyter notebook

Navigate to any lab folder (CV Lab 01, CV Lab 02, CV Lab 03, Lab Assignment 01_CV Lab 04, CV Lab 05, CV Lab 06, CV Lab 07, CV Lab Mid, CV Lab 09, Lab Assignment 02_CV Lab 10, or CV Lab 12) and explore the respective code, notebooks, or documentation.

6. Run the Real-Time Quality Inspection Prototype (Lab 05 Bonus)

cd "CV Lab 05/Bonus Task"
pip install -r requirements.txt
python app.py

Open your web browser at http://127.0.0.1:5000 to interact with the image inspection, conveyor belt video stream, and live webcam inspection modules.


👤 Author & Academic Info

  • Course: Introduction to Computer Vision
  • Student ID: FA23-BAI-013
  • Author: Muhammad Umer Rafiq
  • Program: BS Artificial Intelligence (Semester 7)

📜 License

This project is licensed under the MIT License — feel free to use and adapt this code for academic and educational purposes.

About

Laboratory experiments, assignments, and benchmarks for Computer Vision: spatial filtering, edge detection, deep CNNs, HOG + SVM defect detection, SIFT matching, GA-HOG, BloodMNIST, YOLO fracture detection, ML regression, and CNN layer visualization.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages