Image augmentation
এই পাঠে যা শিখবেন
- Augmentation কেন CV-তে essential
- প্রধান augmentation কৌশল ও কখন কোনটি
- Domain-safe vs unsafe augmentation
- Albumentations-এ pipeline তৈরি
১ · কেন augmentation?
Deep network লক্ষ লক্ষ parameter — train করতে অনেক data চাই। কিন্তু label করা ছবি ব্যয়বহুল। AugmentationData Augmentationএকটি training image-কে রূপান্তর করে নতুন example তৈরি — যাতে label বদলায় না কিন্তু model নতুন variation দেখে। DL-এর key regularization। — একই ছবিকে রূপান্তর করে নতুন example তৈরি, কিন্তু label same রাখা।
১,০০০ বিড়ালের ছবি + augmentation ≈ ১০,০০০ effective examples। Model দেখে — flipped cat, rotated cat, dim-light cat — সবই বিড়াল। Real world deployment-এ এই variation চাই।
২ · Augmentation = regularization
Mathematically, augmentation একটি stochastic transformation $T \sim \mathcal{T}$:
$$\theta^* = \arg\min_\theta \; \mathbb{E}_{(x, y), T} \big[ \mathcal{L}(f_\theta(T(x)), y) \big]$$
প্রতি epoch-এ ভিন্ন $T$ → model কোনো specific augmentation pattern memorize করতে পারে না → overfitting কমে।
৩ · Geometric augmentation
- Horizontal flip: বেশিরভাগ object class symmetry-এ ভাল (cat, car)। Text, hand-handed number-এ ভাঙে।
- Vertical flip: aerial/satellite — useful। Pedestrian, sky photo — আকাশ-নিচু ভুল।
- Rotation: ±10° to ±30° সাধারণ। Bigger rotation — context destroy।
- Random crop + resize: object scale variability। Inception training-এর key।
- Affine/Perspective: document scan-এ realistic distortion।
- Elastic deformation: medical image-এ tissue elasticity simulate।
৪ · Color augmentation
- Brightness/Contrast: ±20% — different lighting condition।
- Hue/Saturation jitter: camera color cast diversity।
- Gamma correction: non-linear brightness — outdoor/indoor।
- Gray scale: sometimes random grayscale convert (SimCLR style)।
- PCA color: AlexNet original — channel covariance basis-এ noise।
৫ · Noise ও occlusion
- Gaussian noise: sensor noise mimic।
- JPEG compression: different quality random — robust to web-uploaded image।
- Cutout / Random Erasing (২০১৭): ছবিতে square mask (zero বা random)। Occlusion robustness।
- Random shadow/sun flare: driving dataset-এ।
৬ · Mixing strategies
- MixUp (২০১৮): দু'টি ছবি linear blend, label-ও blend। $x_{\text{mix}} = \lambda x_1 + (1-\lambda) x_2$।
- CutMix (২০১৯): এক ছবির patch অন্য ছবিতে paste। Label area-proportional।
- Mosaic (YOLOv4): ৪টি ছবি একত্র → multi-scale training।
- AugMix: multiple augmentation chain-এর consistency loss।
৭ · AutoAugment ও RandAugment
- AutoAugment (২০১৯): RL দিয়ে best augmentation policy search। CIFAR/ImageNet-এ SOTA।
- RandAugment: simpler — randomly N transform select, magnitude একই। Tunable, no search।
- TrivialAugment: RandAugment-এর সরলতম version। Surprisingly competitive।
৮ · Domain-safe vs unsafe
Augmentation যেন label না বদলায় — সেটাই critical।
- Cat/dog classification: horizontal flip safe, vertical flip safe (semantically), rotation মাঝারি।
- Digit recognition (MNIST): "6" উল্টালে "9" — vertical flip ভুল! horizontal flip-ও risky (mirror digit)।
- Bangla text OCR: কোনো flip-ই নয়। Character mirror invalid।
- Medical: chest X-ray horizontal flip OK, vertical না (heart চলে যায়)।
- Aerial/Satellite: any rotation OK — orientation arbitrary।
৯ · Albumentations — practical pipeline
import numpy as np
import cv2
# Without Albumentations — pure NumPy/OpenCV demo
def random_augment(img, rng=None):
rng = rng or np.random.default_rng()
# Horizontal flip (50%)
if rng.random() < 0.5:
img = cv2.flip(img, 1)
# Random rotation [-15, 15]
angle = rng.uniform(-15, 15)
h, w = img.shape[:2]
M = cv2.getRotationMatrix2D((w/2, h/2), angle, 1.0)
img = cv2.warpAffine(img, M, (w, h), borderMode=cv2.BORDER_REFLECT)
# Brightness jitter
delta = rng.integers(-25, 25)
img = np.clip(img.astype(int) + delta, 0, 255).astype(np.uint8)
# Cutout — random 30x30 erase
if rng.random() < 0.5:
y, x = rng.integers(0, h-30), rng.integers(0, w-30)
img[y:y+30, x:x+30] = 0
return img
# Demo
img = np.random.randint(50, 200, (100, 100, 3), dtype=np.uint8)
aug = random_augment(img)
print("Original mean:", img.mean(), "Augmented mean:", aug.mean())
A.Compose([A.HorizontalFlip(), A.Rotate(15), ...]) — declarative pipeline।
১০ · Augmentation নিয়ে best practice
- Train only: augmentation training-এ; val/test-এ original।
- On-the-fly: disk-এ pre-augmented store না — every epoch fresh।
- Visualize: training শুরুর আগে augmented ছবি দেখুন — silly হলে detect।
- Tune intensity: পনি augmentation-এ accuracy কমলে — কমান।
- Test-time augmentation (TTA): inference-এ multiple augment + ensemble।
ভাবনার প্রশ্ন
প্র ০১ MixUp-এ দু'টি ভিন্ন class-এর ছবি blend করে label-ও blend। কেন এটি accuracy বাড়ায় — এটা তো "noise"?
MixUp (Zhang et al., 2018) — counter-intuitive কিন্তু effective। Theoretical foundation linear interpolation principle-এ।
Mathematical idea:
- $\tilde{x} = \lambda x_i + (1-\lambda) x_j$, $\tilde{y} = \lambda y_i + (1-\lambda) y_j$।
- $\lambda \sim \text{Beta}(\alpha, \alpha)$ — মোস্টলি 0 বা 1-এর কাছাকাছি।
- Model learns: linear combination of inputs → linear combination of outputs।
কেন কাজ করে?
- Vicinal Risk Minimization: traditional ERM শুধু training point-এ আশা। MixUp — point-এর "vicinity"-তে generalize।
- Linear behavior between classes: decision boundary smooth — sharp না। Adversarial example-এর প্রতি robust।
- Implicit label smoothing: softmax output সর্বদা 0/1 না — overconfident model কম।
- Memorization কমে: exact training image rare → memorize impossible।
Practical gain:
- ImageNet ResNet-50 — 76.3% → 77.9% (+1.6%)।
- CIFAR-10 PreActResNet-18 — 5.6% → 4.2% error।
- Robustness — corrupted CIFAR-10-C-এ significant gain।
কখন কাজ করে না?
- Object detection — bbox-এ MixUp meaningless।
- Very small dataset — model already underfit।
- Class boundary nonlinear — Beta(α=1) too aggressive।
Variants:
- CutMix: blend না, region paste। Detection-এ আরো ভাল।
- Manifold MixUp: hidden layer-এ MixUp — even better।
- FMix: Fourier-domain MixUp।
মূল উপলব্ধি: Augmentation শুধু "data বাড়ানো" না — model-এর inductive bias বদলানো। MixUp linearity bias inject — যা generalize ভাল।
প্র ০২ Object detection-এ augmentation tricky কেন? Bounding box কীভাবে rotate, crop-এ adjust করতে হয়?
Classification-এ label scalar — augmentation-এ unchanged। Detection-এ label = bbox coordinates — augmentation-এ co-transform চাই।
Geometric transform-এ bbox handle:
- Horizontal flip: $x_1' = W - x_2$, $x_2' = W - x_1$ (mirror)।
- Rotation: bbox-এর 4 corner rotate → new axis-aligned bbox। Larger than original (loose)।
- Crop: bbox-কে crop area-এ clip। Bbox area > 50% retain criterion।
- Resize: bbox proportional scale।
Subtle problem — small object loss:
- Crop-এ ছোট object বাইরে চলে যায়।
- Visibility threshold tune করতে হয় — 30% নাকি 50%।
- Small object detection বিশেষ challenge।
Rotation challenge:
- Axis-aligned bbox (most common) — rotated object-এর tight fit না।
- 15° rotate-এ bbox area 30% বেড়ে যেতে পারে।
- Heavy rotation (45°+) avoid করুন বা rotated bbox use করুন।
Photometric (color) — easy:
- Brightness, contrast — bbox unchanged।
- Color jitter — safe সবসময়।
Mosaic (YOLO):
- ৪টি ছবি একত্রে — proper bbox merge।
- Boundary-তে cross-image bbox handle।
- Multi-scale & multi-context training।
Library best practice:
- Albumentations: bbox-aware।
BboxParams(format='pascal_voc')। - imgaug: shape-aware augmentation।
- torchvision v2: recently bbox transforms।
Format conversion:
- Pascal VOC: $(x_1, y_1, x_2, y_2)$।
- COCO: $(x, y, w, h)$।
- YOLO: $(x_c, y_c, w, h)$ normalized।
- Augmentation-এ format consistent চাই।
Segmentation extension:
- Mask-ও co-transform।
- Interpolation: bbox bilinear, mask nearest।
মূল উপলব্ধি: Annotation-aware augmentation — detection/segmentation-এ pipeline complexity-র primary source। Library choose carefully।
প্র ০৩ একটি Bangla handwritten OCR ডেটাসেটে augmentation strategy কী হবে? কোন গুলি safe, কোন গুলি বিপজ্জনক?
Bangla OCR — augmentation choice carefully করতে হয়। ভাষার script-specific constraint।
Bangla character-এর বিশেষত্ব:
- Matra (উপরের horizontal line) — orientation-sensitive।
- Conjunct (যুক্তাক্ষর) — তিন-চার character একসাথে।
- Top-heavy script — vertical orientation matters।
- "হ" আর "ত" — similar; distinction subtle।
UNSAFE augmentation:
- Horizontal flip: "ক" mirror = invalid character। সব Bangla flip ভাঙে।
- Vertical flip: matra নিচে — character unrecognizable।
- Large rotation (>15°): matra confused with diacritic।
- Heavy elastic: conjunct distorted।
SAFE augmentation:
- Small rotation ±5°: handwriting natural variation।
- Translation ±5 pixels: centering variation।
- Mild scaling 90-110%: different writer pressure।
- Brightness ±15%: scan condition।
- Slight blur (σ=0.5): ink bleed simulate।
- Salt-pepper noise (small): paper texture।
- Random thickness (morphology): erosion/dilation 1px।
SPECIAL augmentation (Bangla-specific):
- Slant simulation: right slant (italic-like)।
- Stroke variation: bold vs thin variant।
- Connected component join: intentional smudging।
- Background texture: খাতা / printer paper।
- Low-res then upscale: photo of handwriting।
Synthesizer-based augmentation:
- Font rendering: Unicode-এ different Bangla font (SolaimanLipi, Kalpurush) image render।
- Style transfer: printed text → handwriting style।
- Bornom OCR project — synthetic augmentation দিয়ে dataset 100x বাড়িয়েছিল।
Class-specific care:
- Confusable pair ("০" vs "ও", "১" vs "৭") — extra augmentation না, distinction emphasize।
- Numerals — separate model বা auxiliary loss।
Verification protocol:
- Augmented samples — Bangla speaker-এ visual review।
- If 10% augmented unrecognizable → augmentation too aggressive।
- Held-out test set augmentation-free — true accuracy।
মূল উপলব্ধি: Domain knowledge augmentation choice-এ অপরিহার্য। English NLP/OCR-এর recipe Bangla-তে উল্টো হতে পারে।
প্র ০৪ SimCLR, MoCo-র মতো self-supervised methods augmentation-কে contrastive learning-এর core করেছে। কীভাবে — augmentation কি training signal হয়ে গেছে?
এটি ২০২০-পরবর্তী CV-র বিপ্লব। Augmentation অপ্রত্যাশিতভাবে representation learning-এর foundation হয়ে উঠেছে।
Self-supervised learning idea:
- Label-free pretrain → downstream-এ fine-tune।
- Pretext task: এক ছবির দু'টি augmented view "একই" — অন্য ছবির view "আলাদা"।
- Augmentation = supervision signal define করে।
SimCLR (Chen et al., 2020):
- Each batch image → 2 augmented views।
- Positive pair: same image-এর দু'টি view।
- Negative pair: অন্য সব images।
- Loss: NT-Xent (temperature-scaled cosine similarity)।
Augmentation choice critical:
- SimCLR ablation: random crop + color jitter দু'টি essential।
- Either একটা remove → accuracy 5-10% drop।
- Vertical flip — অপ্রয়োজনীয়।
- "Composition" of strong augmentations — key insight।
কেন augmentation = supervision?
- Augmentation define করে — "এই দু'টি ছবি কি similar?"।
- Crop different region → invariance to spatial position।
- Color jitter → invariance to color shift।
- Strong rotation এড়ান — rotation-equivariance শেখা চাই, invariance না।
MoCo, BYOL, DINO, MAE evolution:
- MoCo: momentum encoder + queue। Less negative-dependent।
- BYOL: negative-free — augmentation alone enough।
- DINO: self-distillation — student/teacher augmented view।
- MAE (Masked Autoencoder): 75% pixel mask — extreme augmentation। Reconstruction-ই pretext।
Theoretical insight:
- Augmentation = data manifold-এর "tangent direction" sampling।
- Model learns features invariant along these tangents।
- Feature space — augmentation-induced equivalence class।
Practical impact:
- ImageNet pretrained → ImageNet self-supervised pretrained।
- Linear probe accuracy: SimCLR 76.5%, MoCo v3 84.1% (close to supervised)।
- Downstream transfer better — especially data-scarce domains।
- Foundation models (CLIP, DINOv2) — augmentation-driven।
Bangla CV-তে implication:
- Bangla-specific labeled data কম। Self-supervised — unlabeled scrape থেকে train।
- Bangla text image, handwriting — DINO-style pretrain promising।
- Augmentation strategy domain-specific tune।
মূল উপলব্ধি: Augmentation = "data engineering" থেকে "representation engineering"-এ promote। Modern CV-র cornerstone।
অনুশীলন
-
Pipeline বানান: ImageNet-style train pipeline — random crop 224, horizontal flip, color jitter — Albumentations syntax-এ লিখুন।
import albumentations as A train = A.Compose([ A.RandomResizedCrop(224, 224, scale=(0.5, 1.0)), A.HorizontalFlip(p=0.5), A.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.05), A.Normalize(mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225]), ]) -
Mosaic logic: ৪টি 320×320 ছবি একত্র করে 640×640 mosaic — bbox কীভাবে adjust হবে?
প্রতিটি ছবির bbox: top-left → +0,+0; top-right → +320,+0; bottom-left → +0,+320; bottom-right → +320,+320। Mosaic boundary cross করলে clip। Bbox visibility threshold (30%+) check করতে হয়।
-
ভাবুন: একটি model 99% train accuracy কিন্তু 60% val। Augmentation কি সমাধান? কতটা সাহায্য করবে?
স্পষ্ট overfitting। Augmentation help করবে — গভীর regularization। আশা করা যায় 60% → 70-75%। কিন্তু dataset যদি খুব ছোট হয় — augmentation alone যথেষ্ট না; transfer learning + augmentation দরকার।
আরও পড়ুন · ABCL TECH-এ আপনার পরবর্তী পদক্ষেপ
- পাঠ ০৯ · CNN পুনরাবৃত্তি পরবর্তী পাঠ Module 2 শুরু — CNN architecture-এ ডুব।
- পাঠ ০৭ · SIFT & HOG আগের পাঠ Module 1-এর last classical lesson।
- পাঠ ১৬ · Transfer learning এগিয়ে Augmentation + transfer = small-data DL-এর পথ।
- সব AI Courses দেখুন ABCL TECH Python, ML, DL, NLP, CV, GenAI, RL, MLOps — সব AI কোর্স একসাথে।