SIFT ও HOG — classical features
এই পাঠে যা শিখবেন
- Feature কী — keypoint vs descriptor
- SIFT-এর চারটি ধাপ
- HOG-এর gradient histogram concept
- OpenCV-তে SIFT ও HOG ব্যবহার
১ · Feature কী?
Feature = ছবির এমন একটি অংশ যা distinctive ও repeatable। ভিন্ন কোণ থেকে, ভিন্ন আলোয়, ভিন্ন আকারে — একই বস্তুর একই feature পাওয়া উচিত।
Two-step process:
- Detection: এই pixel কি interesting? (corner, blob, junction)
- Description: এই pixel-এর চারপাশে কী আছে? (vector representation)
ছবিকে full pixel-এ compare করা impossible। কিন্তু ১০০-২০০ keypoint-এর descriptor compare — fast। এই trick থেকেই panorama stitching, AR, SLAM সম্ভব।
২ · SIFT — চারটি ধাপ
David Lowe (২০০৪) — Scale-Invariant Feature Transform। ১০ বছর CV-র সবচেয়ে cited paper।
ধাপ ১ — Scale-space extrema detection
- ছবিকে কয়েকটি scale-এ Gaussian blur।
- Difference of Gaussians (DoG) — adjacent blur level-এর difference।
- 3D extrema (x, y, scale) — local maxima/minima। এগুলো keypoint candidate।
ধাপ ২ — Keypoint localization
- Sub-pixel refinement — Taylor expansion দিয়ে accurate position।
- Low-contrast point reject।
- Edge response reject (only blob-like keypoint রাখা)।
ধাপ ৩ — Orientation assignment
- Keypoint-এর চারপাশের 16×16 patch।
- Gradient orientation histogram — dominant orientation বেছে।
- একই keypoint-এ একাধিক orientation-ও সম্ভব।
ধাপ ৪ — Descriptor
- Patch rotate — dominant orientation-এ align (rotation invariance)।
- 4×4 sub-region × ৮ orientation bin = ১২৮-D vector।
- Normalize — illumination invariance।
ফলাফল: ছবির যেকোনো বস্তুর scale, rotation, illumination-নির্বিশেষে একই signature।
৩ · SIFT-এর invariance
- Scale: DoG pyramid দিয়ে।
- Rotation: dominant orientation alignment।
- Illumination: gradient (absolute brightness নয়), descriptor normalize।
- Affine (partial): small viewpoint change সহ্য করে — large না।
৪ · SURF, ORB — SIFT-এর বিকল্প
- SURF (২০০৬): Speeded-Up Robust Features — Haar wavelet, integral image। SIFT-এর 3-5x fast।
- ORB (২০১১): Oriented FAST + Rotated BRIEF। SIFT-এর 100x fast, free (SIFT/SURF patented ছিল)।
- BRIEF, FREAK, AKAZE — অন্যান্য fast descriptor।
৫ · HOG — pedestrian detection-এর জাদু
Navneet Dalal & Bill Triggs (২০০৫, CVPR)। মানুষ detect-এর সর্বশ্রেষ্ঠ classical descriptor।
মূল ধারণা: বস্তুর shape — gradient orientation distribution থেকে চিনে নেওয়া যায়। মানুষ-এ — head, shoulder, leg-এর gradient pattern বিশেষ।
HOG-এর pipeline
- Cell: ছবিকে 8×8 pixel cell-এ ভাগ।
- Gradient histogram: প্রতি cell-এ — সব pixel-এর gradient orientation কে ৯টি bin (0-180°)-এ histogram।
- Block normalization: 2×2 cell = 1 block। Block-wise L2 normalization — illumination invariance।
- Descriptor: সব block concatenate — large vector।
- Classifier: SVM train — pedestrian vs non-pedestrian।
৬ · OpenCV-তে SIFT
import cv2
import numpy as np
# একটি synthetic textured image
np.random.seed(42)
img = np.random.randint(0, 256, (200, 200), dtype=np.uint8)
# SIFT
sift = cv2.SIFT_create()
keypoints, descriptors = sift.detectAndCompute(img, None)
print("Keypoint count:", len(keypoints))
print("Descriptor shape:", descriptors.shape) # (N, 128)
print("First keypoint:")
kp = keypoints[0]
print(f" position: ({kp.pt[0]:.1f}, {kp.pt[1]:.1f})")
print(f" size (scale): {kp.size:.2f}")
print(f" angle (orientation): {kp.angle:.1f}°")
print(f" response (strength): {kp.response:.4f}")
৭ · OpenCV-তে HOG
import cv2
import numpy as np
# একটি 64×128 synthetic ছবি (pedestrian detection size)
img = np.zeros((128, 64), dtype=np.uint8)
img[20:100, 20:44] = 200 # vertical body shape
# HOG descriptor
hog = cv2.HOGDescriptor(
_winSize=(64, 128),
_blockSize=(16, 16),
_blockStride=(8, 8),
_cellSize=(8, 8),
_nbins=9
)
descriptor = hog.compute(img)
print("HOG descriptor shape:", descriptor.shape)
# (3780, 1) — Dalal-Triggs original size
# Norm
print("L2 norm:", np.linalg.norm(descriptor))
৮ · DL-পূর্ব যুগে এদের রাজত্ব
- SIFT: Image matching, panorama (Photoshop, Hugin), 3D reconstruction (Photo Tourism), SLAM (ORB-SLAM)।
- HOG+SVM: ২০০৫-২০১২ pedestrian detection benchmark।
- HOG-cascade: Viola-Jones-এর successor।
- Bag of Visual Words: SIFT cluster → image retrieval, classification।
৯ · DL-এ পরিবর্তন
- ২০১২ AlexNet — CNN feature SIFT-এর চেয়ে ভাল। ১০ বছরের race ভেঙে পড়ে।
- ২০১৪ R-CNN — HOG+SVM-এর জায়গায় CNN feature + SVM।
- আজকের SuperPoint, D2-Net, LoFTR — SIFT-এর DL successor।
ভাবনার প্রশ্ন
প্র ০১ SIFT-এর "scale invariance" কীভাবে DoG pyramid দিয়ে অর্জিত হয়? Lindeberg-এর scale-space theory-র মূল insight কী?
Tony Lindeberg (১৯৯৪) — Scale-space theory-র জনক। SIFT-এর গাণিতিক ভিত্তি।
মূল problem:
- একই বস্তু কাছ থেকে — বড় (high resolution detail)।
- দূর থেকে — ছোট (low resolution)।
- একই detector উভয় ক্ষেত্রে কাজ করতে হবে।
Scale-space-এর insight:
- ছবিকে অনেকগুলো $\sigma$-এ Gaussian blur — multi-scale representation।
- $\sigma$ ছোট = fine detail, $\sigma$ বড় = coarse structure।
- একটি বস্তু "natural scale"-এ extremum দেয় — সেটাই keypoint।
DoG-র চমৎকারিত্ব:
- Laplacian of Gaussian (LoG) — scale-space-এর "blob detector"। কিন্তু compute ব্যয়বহুল।
- DoG = $G_\sigma - G_{k\sigma}$ — দু'টি Gaussian-এর difference।
- Mathematical proof: DoG ≈ scale-normalized LoG (Lowe-র paper-এ)।
- ছবিকে একবার pyramid-এ blur করে nearby blur subtract — সাশ্রয়ী।
Octave structure:
- Octave = same resolution-এর কয়েকটি blur level।
- Octave শেষে — ছবি 2x downsample → পরের octave।
- একটি image-এ ৪-৫ octave সাধারণত।
Extremum detection:
- প্রতিটি pixel-এর 26 neighbor (8 same scale + 9 above + 9 below)।
- Local extremum (max বা min) → keypoint candidate।
Keypoint-এর scale:
- যে $\sigma$-এ extremum পাওয়া গেছে — সেটাই keypoint-এর "characteristic scale"।
- Descriptor compute হয় এই scale-এ proportional patch থেকে।
- এটাই scale invariance-এর source।
Theoretical foundation:
- Lindeberg প্রমাণ: Gaussian = unique kernel যা scale-space axioms (causality, semi-group, isotropy) মেনে চলে।
- Heat equation-এর সাথে সম্পর্ক: $\partial L / \partial \sigma = \nabla^2 L$।
- Biological evidence: human retina-এ multi-scale Gaussian-like processing।
মূল উপলব্ধি: SIFT মাটি থেকে design না — গভীর mathematical principle থেকে। এই pure mathematical insight-ই SIFT-কে dominantent করেছিল ১০ বছর।
প্র ০২ HOG pedestrian detection-এ SVM ব্যবহার হয় — কেন simple threshold বা random forest নয়? SVM-এর কী gain?
এটি ML system design-এর একটি classic case study। Choice random ছিল না — গাণিতিক justification আছে।
HOG descriptor-এর nature:
- 3780-D dense feature — high dimensional।
- Each dimension continuous, normalized।
- Pedestrian vs non-pedestrian — generally separable।
SVM-এর fit reason:
- High-D linear separation: SVM linear kernel — simple decision boundary, fast inference।
- Margin maximization: training-এ unseen sample-এ generalize ভাল।
- Sparse support vector: 1000s of training image থেকে শুধু কিছু support vector — memory efficient।
- Probabilistic interpretation: Platt scaling দিয়ে confidence score।
Threshold কেন কাজ করে না?
- Single dimension threshold — ৩৭৮০-D space-এ trivially অসম্পূর্ণ।
- Multi-feature linear combination দরকার — সেটাই SVM।
Random forest কেন কম optimal?
- RF — axis-aligned split। 3780-D-এ explosion।
- Continuous gradient bin — RF-এর discretization-এ subtle pattern lose।
- Inference slower (tree traversal × 100 trees)।
- Model size বড় (each tree large)।
Neural network কেন না?
- ২০০৫-এ — DL মৃতপ্রায়। Training infrastructure ছিল না।
- Small dataset (INRIA — 2400 positive)। MLP overfit।
- SVM-এর margin theory better generalization বলে accepted।
HOG+SVM-এর extension:
- Kernel SVM: RBF, polynomial — non-linear decision। Slower।
- Cascade: multi-stage SVM — early reject easy negative। Realtime।
- Latent SVM (DPM): deformable parts — Felzenszwalb। ২০০৮-২০১২ rules।
Modern parallel:
- CNN feature extractor + linear classifier — same idea, learned features।
- HOG → CNN feature, SVM → softmax linear।
- Architecture continuity!
মূল উপলব্ধি: ML algorithm choice = (1) data nature, (2) compute available, (3) interpretability need-এর intersection। HOG+SVM combination — ২০০৫-এর constraint-এ optimal।
প্র ০৩ SIFT patent-এর কারণে অনেক বছর open-source-এ ছিল না। ২০২০-এ patent expire। এই IP issue CV-র progress কীভাবে আকার দিয়েছে?
এই গল্প — research patent vs open source-এর ক্ষেত্রে CV-র সবচেয়ে চেনা case study।
Background:
- SIFT — University of British Columbia patented (US 6,711,293, ২০০৪-২০২০)।
- Lowe's algorithm — open paper, কিন্তু commercial use restricted।
- OpenCV-তে SIFT non-free module-এ → standard install-এ অনুপস্থিত।
Effect on research:
- Alternative invention: ORB (Rublee et al., 2011) — explicitly "free SIFT alternative"।
- FREAK, BRIEF, AKAZE — patent-free landscape encourage।
- SURF-ও patented — same problem।
- Academic frustration: small research group cannot ship products।
Effect on industry:
- Photo apps — license fee। Photoshop UBC-কে fee দিত।
- Open source projects — alternative develop। OpenSURF, RootSIFT।
- Mobile/AR vendors — ORB choose। Android ARCore এখনো ORB-based।
Patent expiration (March 2020):
- OpenCV-এ SIFT main module-এ free।
- Mobile apps SIFT-এ migrate।
- Tutorials reopen।
- কিন্তু ইতিমধ্যে DL feature (SuperPoint, etc.) উঠে এসেছে।
Broader IP debate:
- Pro patent: University funded basic research, return-on-investment।
- Con patent: Open algorithm faster progress; alternatives waste effort।
- Modern norm: ML papers patent-free, code on GitHub। Open culture।
- Anthropic, OpenAI, Meta: models commercial but research papers free।
Lesson:
- IP friction often spurs innovation in alternatives।
- Open source builds bigger ecosystems — see PyTorch dominance।
- Patent's expiration timing affects technology adoption curves।
Today's parallel:
- Closed model (GPT-4) vs open model (Llama, Mistral)।
- Bangladesh-এর startup — open model-এ ভর করে।
- SIFT story repeating in LLM era।
মূল উপলব্ধি: Algorithm-এর success শুধু গণিত না — license, ecosystem, community-র উপরও। Engineer-এর IP awareness থাকা চাই।
প্র ০৪ আজ ২০২৬-এ একটি AR app বানাচ্ছেন যা phone-এ marker track করে। SIFT, ORB, বা SuperPoint — কোনটা বাছবেন? Trade-offs?
এটি real production decision। Bangladesh-এর AR startup-গুলোর সামনে আজও এই trilemma।
Use case profile:
- Mobile phone — limited compute (~5W TDP)।
- Battery sensitive — multi-hour use।
- 30+ FPS realtime চাই।
- Poor lighting (Bangladesh outdoor / indoor lights mix)।
- Diverse phone hardware (low-end Android থেকে iPhone)।
SIFT — pros & cons:
- ✅ Highest accuracy across illumination/scale।
- ✅ Patent-free now।
- ❌ Slow — 100ms+ per frame even with optimization।
- ❌ Memory-heavy (128-D × hundreds of points)।
- Verdict: high-end iPhone-এ OK, mid-range Android struggle।
ORB — pros & cons:
- ✅ ~10x faster than SIFT।
- ✅ Binary descriptor (256 bit) — memory tiny।
- ✅ Hamming distance — fast matching।
- ❌ Less robust to large viewpoint change।
- ❌ Discriminative power slightly less।
- Verdict: mobile AR-এ default choice। ARCore-এ ব্যবহৃত।
SuperPoint — pros & cons:
- ✅ DL-based — challenging condition (motion blur, low-light) handle।
- ✅ Self-supervised — generalize ভাল।
- ❌ Neural network — GPU/NPU চাই।
- ❌ Mobile model 5-20 MB।
- ❌ Battery drain।
- Verdict: flagship phones (NPU available)-এ best।
Modern hybrid approach:
- ORB initial localization (fast, every frame)।
- Periodic SuperPoint refinement (slow, every 30 frames)।
- Pose drift correct।
- iPhone Lidar + ORB — ARKit।
Recent frontier:
- LoFTR (2021): Detector-free dense matching। Slow but very accurate।
- DISK (2020): Self-supervised local feature।
- Deep VO/SLAM: ORB-SLAM3 (classical) vs DROID-SLAM (DL)।
Bangladesh-specific considerations:
- Mid-range device dominant (Walton, Realme, Redmi)।
- 3G/4G data — model download size matters।
- Outdoor light variation extreme।
- Recommendation: ORB primary, SuperPoint fallback for premium devices।
Decision matrix:
- Premium iOS → ARKit native (ORB+VIO)।
- Premium Android → ARCore (ORB)।
- Mid-range Android → custom ORB pipeline।
- Server-side AR → SuperPoint/LoFTR via cloud।
মূল উপলব্ধি: "Best algorithm" নেই — best algorithm for context আছে। Hardware, energy, accuracy, latency-র multi-objective optimization।
অনুশীলন
-
SIFT match: দু'টি ছবিতে SIFT detect করে BFMatcher দিয়ে match — কোডটি লিখুন।
sift = cv2.SIFT_create() kp1, des1 = sift.detectAndCompute(img1, None) kp2, des2 = sift.detectAndCompute(img2, None) bf = cv2.BFMatcher(cv2.NORM_L2, crossCheck=True) matches = sorted(bf.match(des1, des2), key=lambda m: m.distance) print(f"Top match dist: {matches[0].distance:.2f}") -
HOG dimension: 64×128 window, 16×16 block, 8×8 stride, 8×8 cell, 9 bin — descriptor dimension কত?
Window per dim: $(64-16)/8 + 1 = 7$ horizontal, $(128-16)/8 + 1 = 15$ vertical = 105 block। প্রতি block 4 cell × 9 bin = 36। Total 105 × 36 = 3780।
-
ভাবুন: SIFT keypoint detect-এ DoG-র বদলে Harris corner ব্যবহার করলে কী হতো?
Harris corner = single scale। Scale invariance থাকত না। দূর থেকে নেওয়া ছবিতে keypoint match হতো না। SIFT-এর scale-space pyramid এই সমস্যার সমাধান।
আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ
- পাঠ ০৮ · Image augmentation পরবর্তী পাঠ Module 1-এর শেষ — ML-এর জন্য data prep।
- পাঠ ০৬ · Edge detection আগের পাঠ SIFT/HOG-এর gradient ভিত্তি।
- পাঠ ১১ · AlexNet এগিয়ে যেখানে SIFT-যুগ শেষ — DL-এর জন্ম।
- সব AI Courses দেখুন ABCL TECH Python, ML, DL, NLP, CV, GenAI, RL, MLOps — সব AI কোর্স একসাথে।