Computer Vision Cheat Sheet β€” YOLO, CNN, Segmentation, Augmentation, OCR | Dataplexa
← Back to Cheat Sheets
Sheet icon

Computer Vision Cheat Sheet

CNN Β· YOLO Β· object detection Β· segmentation Β· augmentation Β· OCR Β· ResNet

Sheet 2 of 4 Specialized ML Intermediate Printable

CNN Architecture

Core Building Block

Convolutional Neural Networks extract spatial features by sliding learnable filters across input images through stacked layers.

Convolution Operation
(I * K)(i,j) = Ξ£mΞ£n I(i+m, j+n)Β·K(m,n)
I = input feature map, K = kernel/filter. Output size = ⌊(W βˆ’ K + 2P) / SβŒ‹ + 1. W=input, K=kernel, P=padding, S=stride.
Output Feature Map Size
Hout = ⌊(Hin βˆ’ K + 2P) / SβŒ‹ + 1
Same padding (P = K/2) keeps spatial dims. Valid padding (P=0) shrinks output.
Layer TypePurposeKey Param
Conv2DFeature extractionfilters, kernel, stride
BatchNormStabilise trainingmomentum, Ξ΅
ReLUNon-linearityβ€”
MaxPoolSpatial downsamplingpool_size, stride
DropoutRegularisationrate (0.2–0.5)
Flatten3D β†’ 1D vectorβ€”
DenseClassification headunits, activation
PyTorch β€” Simple CNN Block
import torch.nn as nn

class ConvBlock(nn.Module):
  def __init__(self, in_c, out_c):
    super().__init__()
    self.block = nn.Sequential(
      nn.Conv2d(in_c, out_c,
        kernel_size=3, padding=1),
      nn.BatchNorm2d(out_c),
      nn.ReLU(inplace=True),
      nn.MaxPool2d(2, 2)
    )
  def forward(self, x):
    return self.block(x)
Receptive field: Each neuron "sees" a growing patch of the original image. Deeper layers capture larger, more abstract features β€” edges β†’ textures β†’ objects.

Pretrained Models

Transfer Learning
ModelParamsTop-1 (ImageNet)Best For
VGG16138M71.5%Baseline, feature extraction
ResNet-5025M76.1%General backbone
EfficientNet-B05.3M77.1%Mobile / lightweight
ViT-B/1686M81.8%Large datasets, patches
ConvNeXt-T28M82.1%Modern CNN baseline
DINOv2307M86.2%Self-supervised features
Fine-tuning ResNet-50 (PyTorch)
from torchvision import models
model = models.resnet50(weights='IMAGENET1K_V2')

# Freeze backbone
for p in model.parameters():
  p.requires_grad = False

# Replace classification head
model.fc = nn.Linear(2048, num_classes)
Residual connections in ResNet solve the vanishing gradient problem: output = F(x) + x. Allows training very deep networks (50–152+ layers).

Object Detection

YOLO Β· R-CNN Β· SSD
ModelTypeSpeedAccuracy
R-CNN2-stageSlowHigh
Fast R-CNN2-stageMediumHigh
Faster R-CNN2-stage~5 fpsVery High
SSD1-stage~46 fpsMedium
YOLOv81-stage~160 fpsHigh
DETRTransformer~28 fpsVery High
IoU β€” Intersection over Union
IoU = Area(A ∩ B) / Area(A βˆͺ B)
Measures bounding box overlap. IoU β‰₯ 0.5 = True Positive (PASCAL VOC). IoU β‰₯ 0.75 = stricter COCO threshold.
NMS (Non-Maximum Suppression): Removes duplicate detections. Keeps the highest-confidence box; suppresses overlapping boxes with IoU above threshold (typically 0.4–0.5).

YOLO β€” You Only Look Once

Real-Time Detection

YOLO divides the image into an SΓ—S grid. Each cell predicts B bounding boxes + confidence scores + C class probabilities β€” all in a single forward pass.

YOLO Confidence Score
Conf = P(Object) Γ— IoUpredtruth
High confidence = high probability an object exists AND the box is accurate. Zero if no object in cell.
YOLO Loss Function
L = Ξ»coordLbox + Lobj + Ξ»noobjLnoobj + Lcls
Ξ»coord=5 upweights localisation. Ξ»noobj=0.5 downweights empty cells. CIoU loss in YOLOv8.
VersionKey Improvement
YOLOv1Single pass, 7Γ—7 grid, 45fps
YOLOv3Multi-scale anchors, Darknet-53
YOLOv5PyTorch, CSP backbone, auto-anchor
YOLOv8Anchor-free, C2f module, best default
YOLOv8 β€” Inference & Training
from ultralytics import YOLO

# Load pretrained model
model = YOLO('yolov8n.pt')   # nano

# Inference on image/video
results = model.predict(
  'image.jpg',
  conf=0.25,   # confidence threshold
  iou=0.45,    # NMS IoU threshold
  device='cuda'
)

# Fine-tune on custom dataset
model.train(
  data='dataset.yaml',
  epochs=100,
  imgsz=640,
  batch=16,
  lr0=0.01
)

# Access results
for r in results:
  print(r.boxes.xyxy)   # bbox coords
  print(r.boxes.conf)   # confidence
  print(r.boxes.cls)    # class IDs
Model sizes: YOLOv8n (nano, 3.2M params) β†’ YOLOv8s β†’ YOLOv8m β†’ YOLOv8l β†’ YOLOv8x (68.2M params). Start with nano, scale up if mAP is insufficient.

Image Segmentation

Semantic Β· Instance Β· Panoptic
TypeOutputModel
SemanticClass label per pixelFCN, DeepLab, SegFormer
InstanceSeparate mask per objectMask R-CNN, YOLO-seg
PanopticSemantic + InstancePanoptic FPN, Mask2Former
SAMPrompt-based any maskSegment Anything (Meta)
U-Net Architecture (PyTorch)
# Encoder-Decoder with skip connections
# Encoder: downsample (Conv + Pool)
# Bottleneck: deepest feature map
# Decoder: upsample + concat skip

enc1 = ConvBlock(1, 64)    # 572β†’572
pool1 = nn.MaxPool2d(2)   # 572β†’286
# ... deeper layers ...
up = nn.ConvTranspose2d(512, 256,
           kernel_size=2, stride=2)
x = torch.cat([up, skip], dim=1)
Dice Loss (Segmentation)
Dice = 1 βˆ’ (2|P∩G| + Ξ΅) / (|P| + |G| + Ξ΅)
P = predicted mask, G = ground truth. Ξ΅ prevents division by zero. Better than CE for class-imbalanced masks.

Data Augmentation

Regularisation Β· Diversity
TechniqueWhat it doesUse case
HorizontalFlipMirror image left-rightGeneral (not text)
RandomCropRandom crop + resizeClassification
ColorJitterBrightness/contrast/satLighting variation
RandomRotationRotate Β±degreesOrientation-agnostic
GaussianBlurBlur with Οƒ rangeFocus robustness
NormalizeMean/std per channelAlways apply last
MixupBlend 2 images + labelsClassification boost
CutMixPaste patches + labelsImageNet SOTA
Albumentations Pipeline
import albumentations as A

train_tfm = A.Compose([
  A.RandomResizedCrop(224, 224),
  A.HorizontalFlip(p=0.5),
  A.ColorJitter(
    brightness=0.2, contrast=0.2),
  A.Normalize(
    mean=[0.485,0.456,0.406],
    std=[0.229,0.224,0.225]),
])

Evaluation Metrics

mAP Β· IoU Β· Dice
Mean Average Precision (mAP)
mAP = (1/|C|) Ξ£c APc
AP = area under precision-recall curve per class. mAP@0.5 = IoU threshold 0.5. mAP@[.5:.95] = COCO standard (avg over 10 thresholds).
MetricTaskFormula
IoUDetectionIntersection / Union
mAP@0.5DetectionAP avg over classes @IoU=0.5
mAP@[.5:.95]COCOAvg mAP over 10 IoU thresholds
Dice / F1Segmentation2TP / (2TP + FP + FN)
Pixel Acc.Segmentationcorrect pixels / total pixels
mIoUSemantic segMean IoU across all classes
Class imbalance: Pixel accuracy is misleading when background dominates. Always report mIoU or Dice for segmentation tasks.

OCR Pipeline

Text Detection Β· Recognition
  1. Preprocessing β€” grayscale, denoise, deskew, binarize (Otsu threshold)
  2. Text Detection β€” locate text regions (CRAFT, DBNet, EAST)
  3. Text Recognition β€” read characters per region (CRNN + CTC loss)
  4. Post-processing β€” spell check, NLP cleanup, structured output
EasyOCR β€” Quick Start
import easyocr

reader = easyocr.Reader(['en'])
results = reader.readtext('image.jpg')
for (bbox, text, conf) in results:
  print(f"{text} ({conf:.2f})")
PaddleOCR / Tesseract
# PaddleOCR (fast, accurate)
from paddleocr import PaddleOCR
ocr = PaddleOCR(lang='en')
res = ocr.ocr('img.jpg')

# Tesseract (classic, offline)
import pytesseract
from PIL import Image
text = pytesseract.image_to_string(
  Image.open('img.png'))
CTC Loss (Sequence Recognition)
LCTC = βˆ’log P(y* | x)
Connectionist Temporal Classification β€” aligns variable-length sequences without needing character-level labels. Used in CRNN for scene text recognition.

Image Preprocessing

Normalisation Β· Resize
Standard ImageNet Preprocessing
from torchvision import transforms

preprocess = transforms.Compose([
  transforms.Resize(256),
  transforms.CenterCrop(224),
  transforms.ToTensor(),
  transforms.Normalize(
    mean=[0.485, 0.456, 0.406],
    std=[0.229, 0.224, 0.225]
  )
])
OperationWhy
Resize to 224Γ—224Standard input for ImageNet models
ToTensorPIL [0,255] β†’ float32 [0,1]
NormalizeZero-mean unit-variance per channel
BGR→RGBOpenCV reads BGR; most models expect RGB
Channel firstPyTorch: [C,H,W]; TF: [H,W,C]
Don't forget: Apply the same mean/std normalization at inference as during training. Mismatched normalization is a common silent bug that drops accuracy significantly.

Vision Transformers (ViT)

Patch-Based Attention

ViT splits the image into fixed-size patches, flattens them into tokens, and applies standard transformer self-attention.

Patch Embedding
xp = Flatten(patch) Β· E + Epos
Image HΓ—WΓ—C split into N = HW/PΒ² patches of size PΓ—P. Each patch projected to embedding dim D. Learnable positional embeddings added.
ModelPatchLayersParams
ViT-B/1616Γ—161286M
ViT-L/1616Γ—1624307M
Swin-T4Γ—4Hierarchical28M
DeiT-S16Γ—161222M
CNN vs ViT: CNNs excel with small datasets (inductive bias: locality, translation invariance). ViTs excel with large datasets β€” no spatial bias, global attention from layer 1.

CV Libraries & Tools

Ecosystem Reference
LibraryUse CaseKey Feature
OpenCVImage I/O, preprocessingC++ speed, 2500+ algos
PillowSimple image opsEasy Python interface
torchvisionPyTorch CV utilsPretrained models, transforms
timmModel zoo700+ pretrained CV models
albumentationsAugmentationFastest, bbox-aware transforms
ultralyticsYOLO detectionYOLOv8, simple API
detectron2Research detectionMask R-CNN, Faster R-CNN
supervisionAnnotation utilsWorks with any detector
OpenCV β€” Common Operations
import cv2
import numpy as np

# Read / write
img = cv2.imread('img.jpg')        # BGR
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Resize
img = cv2.resize(img, (224, 224))

# Grayscale + threshold
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
_, thresh = cv2.threshold(
  gray, 127, 255, cv2.THRESH_BINARY)

# Edge detection
edges = cv2.Canny(gray, 100, 200)

# Draw bounding box
cv2.rectangle(img, (x1,y1), (x2,y2),
  (0,255,0), 2)
timm library: import timm; model = timm.create_model('efficientnet_b0', pretrained=True, num_classes=10) β€” fastest way to get any pretrained CV model.

Computer Vision Mastery Checklist

Self-Assessment

CNN Foundations

  • Calculate output size of a Conv2D layer given kernel, stride, padding
  • Explain max pooling and its effect on spatial dimensions
  • Describe residual connections and why they help training
  • Fine-tune a pretrained ResNet for a custom classification task
  • Choose the right pretrained backbone for speed vs accuracy
  • Apply ImageNet normalization correctly at train and inference time

Detection & Segmentation

  • Explain IoU and how it's used as a detection threshold
  • Describe Non-Maximum Suppression and when to adjust the threshold
  • Distinguish semantic vs instance vs panoptic segmentation
  • Train a YOLOv8 model on a custom dataset with dataset.yaml
  • Interpret mAP@0.5 and mAP@[.5:.95] for detection results
  • Apply Dice loss for class-imbalanced segmentation problems

Augmentation, OCR & ViT

  • Build an augmentation pipeline with Albumentations
  • Apply Mixup or CutMix to improve classification accuracy
  • Set up an OCR pipeline using EasyOCR or PaddleOCR
  • Explain CTC loss and why it's needed for sequence recognition
  • Compare CNN vs ViT for small vs large dataset scenarios
  • Use timm to load any pretrained vision model in 2 lines

Next up in Specialized ML β†’ Sheet 3 covers Time Series: ARIMA, LSTM, stationarity testing, lag features, ACF/PACF, and forecasting pipelines.

3 Β· Time Series Cheat Sheet β†’
← Back