Last Night Exam Preparation | All Topics at a Glance
Global, Adaptive, Otsu's Method | Bimodal Histogram | Variance
Erosion, Dilation, Opening, Closing, Top-Hat | Structuring Elements
Image Smoothing, Median Filter, 1st & 2nd Order Derivatives
Gaussian, Salt & Pepper, Poisson, Speckle | Mathematical Models
Mean, Median, Gaussian, Adaptive Filter | Math
Scenario-based | Mathematical Methods | Type Selection
M Matrix, Eigenvalues, Corner Response Function
Translation, Rotation, Scaling, Shearing, Homogeneous Coordinates
Layers: Input, Hidden, Output | Activation Functions
Chain Rule, Loss, Gradient Descent | Network Flow
SGD, Momentum, Adam | When to Use
Patch Embedding, Self-Attention, Key Terms
Convolution, Pooling, FC Layers | Architecture Diagram
Layer-by-Layer Walkthrough | How It Works
Ch-8, Ch-9 | Top exam questions + answers
Ch-10 | Top exam questions + answers
Ch-11 | Top exam questions + answers
Ch-12, Ch-13 | Top exam questions + answers
Ch-14 | Top exam questions + answers
Ch-15–18 | Top exam questions + answers
Ch-19, Ch-20 | Top exam questions + answers
Ch-21 | Top exam questions + answers
Thresholding converts a grayscale image into a binary image (0 or 1) by comparing each pixel intensity to a threshold value \(T\).
DefinitionWhere \(f(x,y)\) is the input pixel intensity and \(g(x,y)\) is the output binary pixel.
Computes a different threshold \(T\) for each pixel based on its local neighbourhood.
Where:
| Method | T Calculation |
|---|---|
| Mean | Average of neighbourhood |
| Weighted (Gaussian) | Gaussian-weighted average (center pixels weigh more) |
| Median | Median of neighbourhood values |
Fully automatic global thresholding. Finds optimal \(T\) that maximizes between-class variance and minimizes within-class variance.
Exam ImportantSimplified form:
$$ \sigma_B^2(k) = \omega_0(k) \cdot \omega_1(k) \cdot \left[\mu_0(k) - \mu_1(k)\right]^2 $$Total variance: \(\sigma_T^2 = \sigma_B^2 + \sigma_W^2\) (constant)
Optimal threshold \(T^*\): value of \(k\) that maximizes \(\sigma_B^2(k)\) (equivalently minimizes \(\sigma_W^2\)).
A small template/mask (e.g., 3×3 square, disk, cross) that slides over the binary image performing logical operations.
Common SEs: BOX(3,3), DISK(5), RING(5), CROSS(3), LINE(r,angle)
Expands foreground objects, fills small gaps/holes.
For binary: pixel becomes 1 if any SE-position overlaps foreground (logical OR).
3×3 all-1 SE on a 3×3 block of 1s → output becomes 5×5 block of 1s (expanded by 1 pixel on each side).
Shrinks foreground objects, removes small/thin structures.
For binary: pixel becomes 1 only if all SE-positions fall on foreground (logical AND).
3×3 all-1 SE on a 3×3 block of 1s → output becomes a single central pixel (shrunk by 1 pixel on each side).
Erosion first, then Dilation.
Result: large block preserved, any 1×1 or 2×2 isolated noise removed.
Dilation first, then Erosion.
Result = difference between dilated and eroded = thickened boundary/edge of objects.
This is a simple edge detector for binary/grayscale images.
Dilation EXPANDS white/foreground: every white pixel grows into its neighbours. Effects: objects get fatter, small gaps close, thin breaks join, tiny dark holes fill.
1. Dilation: \((I \oplus SE)(x,y) = \max_{(s,t)\in SE} f(x{+}s, y{+}t)\) — OR logic, expands
2. Erosion: \((I \ominus SE)(x,y) = \min_{(s,t)\in SE} f(x{-}s, y{-}t)\) — AND logic, shrinks
3. Opening: \(I \circ SE = (I \ominus SE) \oplus SE\) — E then D, removes small bright dots
4. Closing: \(I \bullet SE = (I \oplus SE) \ominus SE\) — D then E, fills small dark holes
5. Gradient: \(G = (I \oplus SE) - (I \ominus SE)\) — dilated minus eroded = boundary outline
Original minus Opening
Closing minus Original
Removes high-frequency noise by averaging/filtering. Smoothing = blurring the image.
3×3 mean kernel: \(\frac{1}{9}\begin{bmatrix}1&1&1\\1&1&1\\1&1&1\end{bmatrix}\)
Averages all pixels in neighbourhood. Blurs edges equally. Good for uniform noise.
3×3 Gaussian kernel (approx, \(\sigma \approx 0.85\)):
$$ \frac{1}{16}\begin{bmatrix}1&2&1\\2&4&2\\1&2&1\end{bmatrix} $$Center pixels get more weight. Preserves edges better than mean filter.
Sorts all pixel values in neighbourhood and picks the middle value.
Smooths flat areas but preserves edges: weights fall when intensity differs a lot.
| # | Filter | Math idea | Best for |
|---|---|---|---|
| 1 | Mean (Box) | Average of neighbourhood | Uniform/Gaussian noise, simple |
| 2 | Gaussian | Weighted average, centre matters most | Gaussian noise, pre-Sobel smoothing |
| 3 | Median | Middle value after sorting | Salt & pepper (impulse) noise |
| 4 | Bilateral | Spatial + intensity weighting | Denoise while keeping edges sharp |
Detects edges by computing gradient magnitude and direction using two 3×3 kernels.
Exam ImportantDetects vertical edges
Detects horizontal edges
Note: Center row/column has weight 2 (Gaussian smoothing in perpendicular direction).
Edge direction is perpendicular to gradient direction.
| Magnitude | Classification |
|---|---|
| \(G > T\) | Strong edge |
| \(T/2 < G \leq T\) | Weak edge |
| \(G \leq T/2\) | Non-edge |
Edge = zero-crossing of the Laplacian. Positive → peak, Negative → valley, sign change = edge.
After applying Laplacian, scan output. A zero-crossing occurs when:
2nd derivative amplifies noise. Practical solution:
Laplacian of Gaussian (LoG): First smooth with Gaussian, then apply Laplacian.
$$ \text{LoG kernel} = \nabla^2 G(x,y) = -\frac{1}{\pi\sigma^4}\left(1 - \frac{x^2+y^2}{2\sigma^2}\right)e^{-\frac{x^2+y^2}{2\sigma^2}} $$Additive noise. Each pixel value has random noise added from a Gaussian distribution. Caused by electronic circuit noise, sensor heat.
\(\mu\) = mean of noise, \(\sigma\) = standard deviation (higher = more noise). Typically \(\mu = 0\) for zero-mean noise.
Random pixels become either white (255, salt) or black (0, pepper). Caused by transmission errors, dead/hot pixels.
\(p_p\) = probability of noise (e.g., 0.1 means 10% pixels corrupted).
Noise inherent to photon counting. Follows Poisson distribution. Common in low-light photography.
\(\lambda\) = average number of photons collected. Variance = mean = \(\lambda\).
When \(\lambda\) is large, Poisson approximates Gaussian with \(\sigma^2 = \lambda\).
Multiplicative noise. Common in radar, ultrasound, SAR imaging.
Noise is proportional to pixel intensity — brighter regions have more absolute noise.
Replaces each pixel with the average of its \(m \times n\) neighbourhood. Linear. Blurs edges. Best for Gaussian noise.
Non-linear. Sorts neighbourhood values, picks middle. Best for salt & pepper noise. Preserves edges better than mean.
\(\sigma\) controls smoothing: larger \(\sigma\) = more blur = more noise removed but edges also blurred.
Separable: 2D Gaussian = product of two 1D Gaussians (efficiency trick).
Adjusts behaviour based on local statistics. Preserves edges while removing noise.
How it works:
Works in levels. Increases window size until conditions met:
Level A: \(A_1 = z_{med} - z_{min}\), \(A_2 = z_{med} - z_{max}\). If \(A_1 > 0\) and \(A_2 < 0\), go to Level B. Else increase window size.
Level B: \(B_1 = z_{xy} - z_{min}\), \(B_2 = z_{xy} - z_{max}\). If \(B_1 > 0\) and \(B_2 < 0\), output \(z_{xy}\). Else output \(z_{med}\).
Where \(z_{min}, z_{max}, z_{med}\) are min, max, median of current window; \(z_{xy}\) is center pixel.
Partitioning an image into meaningful regions (objects vs background, or multiple objects).
Simple, fast. Works when classes have distinct intensity ranges.
Start from seed pixels. Grow region by adding neighbouring pixels that satisfy a similarity criterion (intensity difference < threshold).
Where \(\mu_R\) = mean intensity of current region \(R\).
Detect edges first (Sobel, Canny). Then close gaps and fill enclosed regions. Use edge boundaries to define segments.
Iterate: update means \(\mu_j\), reassign pixels until convergence.
| Scenario | Best Method | Why |
|---|---|---|
| Document with black text on white | Global Thresholding / Otsu | Bimodal histogram, uniform lighting |
| Image with shadows | Adaptive Thresholding | Non-uniform illumination |
| Medical image (tumor on uniform tissue) | Region Growing | Similar intensity, connected region |
| Multiple colored objects | K-means Clustering | Multiple intensity/color classes |
| Object boundaries needed | Edge-based (Canny) | Sharp intensity changes at boundaries |
| Texture-based regions | Texture analysis + clustering | Intensity alone insufficient |
Segment in colour space (RGB / HSV) instead of grayscale when objects differ by colour, not intensity. HSV is preferred: Hue separates colour from lighting.
| Type | Operator | Math |
|---|---|---|
| 1. Roberts (2×2, fastest) | \(G_x = \begin{bmatrix}1&0\\0&-1\end{bmatrix}\), \(G_y = \begin{bmatrix}0&1\\-1&0\end{bmatrix}\) | \(G = \sqrt{G_x^2+G_y^2}\) |
| 2. Prewitt (3×3, uniform weights) | \(G_x = \begin{bmatrix}-1&0&1\\-1&0&1\\-1&0&1\end{bmatrix}\) | Same magnitude formula; less noise-sensitive than Roberts |
| 3. Sobel (3×3, centre ×2) | \(G_x = \begin{bmatrix}-1&0&1\\-2&0&2\\-1&0&1\end{bmatrix}\) | \(G = \sqrt{G_x^2+G_y^2}\), \(\theta = \tan^{-1}(G_y/G_x)\) |
Corner = point where intensity changes significantly in all directions. Detects stable, repeatable feature points.
Exam ImportantWhere \(W\) is the window, \((u,v)\) is the shift.
Where \(I_x = \frac{\partial I}{\partial x}\), \(I_y = \frac{\partial I}{\partial y}\).
Eigenvalues of \(M\): \(\lambda_1, \lambda_2\)
| Case | Eigenvalues | Shape |
|---|---|---|
| Flat region | \(\lambda_1 \approx 0, \lambda_2 \approx 0\) | No change in any direction |
| Edge | \(\lambda_1 \gg \lambda_2 \approx 0\) | Change along one direction only |
| Corner | \(\lambda_1 \gg 0, \lambda_2 \gg 0\) | Change in all directions |
\(k\) = empirically chosen constant (typically 0.04 – 0.06).
The corner response \(R\) bisects every pixel into 3 regions by threshold \(T\):
\(s_x > 1\) = stretch horizontally, \(s_x < 1\) = shrink. \(s_x = s_y\) = uniform scaling.
Rotate point \((x,y)\) by angle \(\theta\) about the origin:
Derivation:
Properties: \(\det(R) = \cos^2\theta + \sin^2\theta = 1\) (preserves area), \(R^T R = I\) (orthogonal), \(R^{-1} = R_{-\theta}\).
Shifts every point by \((t_x, t_y)\). Cannot be represented as a simple 2×2 matrix multiplication (requires homogeneous coordinates).
\(x' = x + sh_x \cdot y\), \(y' = y\)
\(x' = x\), \(y' = sh_y \cdot x + y\)
Shearing slants the image. A square becomes a parallelogram.
Represent 2D point \((x,y)\) as 3D: \((x, y, 1)\). This allows translation to be expressed as matrix multiplication.
Translation:
$$ T = \begin{bmatrix} 1 & 0 & t_x \\ 0 & 1 & t_y \\ 0 & 0 & 1 \end{bmatrix} $$Scaling:
$$ S = \begin{bmatrix} s_x & 0 & 0 \\ 0 & s_y & 0 \\ 0 & 0 & 1 \end{bmatrix} $$Rotation:
$$ R_\theta = \begin{bmatrix} \cos\theta & -\sin\theta & 0 \\ \sin\theta & \cos\theta & 0 \\ 0 & 0 & 1 \end{bmatrix} $$Shearing (X):
$$ Sh_x = \begin{bmatrix} 1 & sh_x & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{bmatrix} $$5th type — Reflection / Mirroring (Ch-14):
$$ F_x = \begin{bmatrix} -1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1 \end{bmatrix}, \quad F_y = \begin{bmatrix} 1 & 0 & 0 \\ 0 & -1 & 0 \\ 0 & 0 & 1 \end{bmatrix} $$Flips the image across an axis. \(\det(F) = -1\) (orientation reversing) — unlike rotation with \(\det = +1\).
| # | Type | What it does | 2D matrix |
|---|---|---|---|
| 1 | Translation | Shift by \((t_x,t_y)\) | Needs homogeneous 3×3 \(T\) |
| 2 | Rotation | Rotate by \(\theta\) about origin | \(\begin{bmatrix}\cos\theta&-\sin\theta\\\sin\theta&\cos\theta\end{bmatrix}\) |
| 3 | Scaling | Resize by \((s_x,s_y)\) | \(\begin{bmatrix}s_x&0\\0&s_y\end{bmatrix}\) |
| 4 | Shearing | Slant; square → parallelogram | \(\begin{bmatrix}1&sh_x\\sh_y&1\end{bmatrix}\) |
| 5 | Reflection | Mirror across axis | \(\begin{bmatrix}-1&0\\0&1\end{bmatrix}\) or \(\begin{bmatrix}1&0\\0&-1\end{bmatrix}\) |
Multiply matrices in order of application (right to left):
Applied as: Scale first, then Rotate, then Translate.
A neural network is a computational model inspired by biological neurons. It learns to map inputs to outputs by adjusting weights through training.
| Layer | Role | Details |
|---|---|---|
| Input Layer | Receives raw data | One neuron per feature/pixel. No computation, just passes values forward. |
| Hidden Layer(s) | Feature extraction | Applies weights, bias, and activation function. Can have multiple layers (deep network). Each neuron computes: \(z = \sum w_i x_i + b\), then \(a = f(z)\). |
| Output Layer | Final prediction | Produces the output. Activation depends on task: sigmoid (binary), softmax (multi-class), linear (regression). |
Introduce non-linearity. Without them, stacked linear layers = single linear layer.
| Function | Formula | Range | Use |
|---|---|---|---|
| Sigmoid | \(\sigma(z) = \frac{1}{1+e^{-z}}\) | (0, 1) | Binary classification output |
| Tanh | \(\tanh(z) = \frac{e^z - e^{-z}}{e^z + e^{-z}}\) | (-1, 1) | Hidden layers (zero-centered) |
| ReLU | \(f(z) = \max(0, z)\) | [0, ∞) | Most common hidden layer |
| Leaky ReLU | \(f(z) = \max(\alpha z, z)\), \(\alpha=0.01\) | (-∞, ∞) | Prevents dead neurons |
| Softmax | \(S(z_i) = \frac{e^{z_i}}{\sum_j e^{z_j}}\) | [0, 1], sum=1 | Multi-class output |
| Term | Definition |
|---|---|
| Loss Function \(L(\hat{y}, y)\) | Measures how far predictions \(\hat{y}\) are from true labels \(y\). E.g., MSE: \(L = \frac{1}{N}\sum(\hat{y}-y)^2\), Cross-entropy: \(L = -\sum y \log \hat{y}\) |
| Weights \(w\) | Learnable parameters connecting neurons. \(z = wx + b\). |
| Bias \(b\) | Additional parameter that shifts the activation function. |
| Forward Pass | Compute output: input → weighted sum → activation → ... → output → loss |
| Backward Pass | Compute gradients of loss w.r.t. each weight using the chain rule. |
| Chain Rule | \(\frac{\partial L}{\partial w} = \frac{\partial L}{\partial \hat{y}} \cdot \frac{\partial \hat{y}}{\partial z} \cdot \frac{\partial z}{\partial w}\) |
| Learning Rate \(\eta\) | Step size for weight updates. Too large = diverge, too small = slow convergence. |
| Gradient Descent | \(w_{new} = w_{old} - \eta \cdot \frac{\partial L}{\partial w}\) |
| Problem | Cause | Symptom | Fix |
|---|---|---|---|
| Vanishing gradient | Many small derivatives multiplied (sigmoid/tanh saturate, \(f' \le 0.25\)) | Early layers stop learning | ReLU, BatchNorm, residual links, careful init |
| Exploding gradient | Large weights \(\times\) large derivatives compound | Loss = NaN, weights blow up | Gradient clipping, smaller LR, BatchNorm |
Combines Momentum + RMSProp. Maintains both first moment (mean) and second moment (variance) of gradients.
Default: \(\beta_1 = 0.9\), \(\beta_2 = 0.999\), \(\epsilon = 10^{-8}\).
| Optimizer | When to Use |
|---|---|
| SGD | Simple problems, convex loss, when you want fine control. Good generalization. |
| SGD + Momentum | Most deep learning tasks. Good default. Faster than plain SGD. |
| Adam | Fast prototyping, sparse gradients (NLP), non-stationary objectives. Default choice for most problems. |
| RMSProp | RNNs, non-stationary targets. Adapts learning rate per parameter. |
\(\eta\) = step size in \(w \leftarrow w - \eta \nabla L\). Too large = overshoot/diverge; too small = slow crawl or stuck. Schedules: step decay, exponential decay, cosine annealing.
| Overfitting | Underfitting | |
|---|---|---|
| Meaning | Memorises training noise; train loss low, val loss high | Too simple; both train and val loss high |
| Looks like | Huge gap between train/val curves | Both curves flat and high |
| Fix | More data, augmentation, dropout, weight decay, early stopping | Bigger model, more epochs, higher LR, better features |
Split an image into fixed-size patches, linearly embed them, add positional encodings, and feed to a standard Transformer encoder.
| Term | Definition |
|---|---|
| Patch Embedding | Convert image patches to vectors. Each \(P \times P \times 3\) patch → \(D\)-dim vector via linear projection. |
| Self-Attention | Each patch attends to all other patches. Computes relationships: \(\text{Attention}(Q,K,V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V\) |
| Multi-Head Attention | Multiple attention heads in parallel, each learning different relationships. Concatenated and projected. |
| [CLS] Token | Special learnable token prepended to sequence. Its final representation used for classification. |
| Positional Encoding | Learnable embeddings added to patch tokens to encode spatial position (ViT uses learnable, not sinusoidal). |
| Layer Norm | Applied before (pre-norm) each sub-layer. Stabilizes training. |
| MLP | Two linear layers with GELU activation. Hidden dim = 4× embedding dim. |
Convolutional layers extract features (edges, textures, shapes). Pooling layers reduce spatial dimensions. FC layers perform classification.
Slides kernels/filters over input. Each kernel detects specific features.
Applied element-wise after convolution. Introduces non-linearity.
Max Pooling: Takes maximum value in each window. Reduces spatial dimensions, provides translation invariance.
Average Pooling: Takes mean of each window.
Flattens feature maps into 1D vector. Each neuron connected to all previous neurons. Final layers for classification.
| Layer Depth | Learns | Example |
|---|---|---|
| Early layers | Low-level features | Edges, corners, colors |
| Middle layers | Mid-level features | Textures, patterns, shapes |
| Deep layers | High-level features | Objects, faces, scenes |
Spreads kernel taps by dilation rate \(r\): a 3×3 kernel with \(r=2\) sees a 5×5 area with only 9 weights. Grows receptive field without extra parameters or downsampling.
Each Transformer encoder layer in ViT consists of two sub-layers with residual connections and layer normalization.
Where \(d_k = D/h\) (embedding dim / number of heads).
Hidden dimension = \(4D\) (4x embedding dim).
| Aspect | CNN | ViT |
|---|---|---|
| Receptive field | Local (grows with depth) | Global (from first layer) |
| Inductive bias | Translation invariance, locality | None (learns from data) |
| Data requirement | Less data needed | Needs large dataset or pretraining |
| Spatial structure | Preserved via pooling | Flattened (positional encoding restores) |
Answer: Thresholding converts grayscale to binary by comparing each pixel to \(T\):
Global thresholding (single \(T\) for whole image) fails under uneven illumination or non-bimodal histograms. Fix: adaptive thresholding (local \(T\) per neighbourhood) or Otsu's method (automatic optimal \(T\)).
Answer: Automatic threshold selection for bimodal histograms. It picks \(T^*\) that maximises between-class variance (equivalently minimises within-class variance):
where \(w_0,w_1\) = class probabilities, \(\mu_0,\mu_1\) = class means. Fails when histogram is not bimodal or lighting is uneven.
Answer:
Dilation (expands white): \((I \oplus SE)(x,y) = \max_{(s,t)\in SE} f(x{+}s,y{+}t)\) — OR logic
Erosion (shrinks white): \((I \ominus SE)(x,y) = \min_{(s,t)\in SE} f(x{-}s,y{-}t)\) — AND logic
What dilation does: every foreground pixel grows into neighbours — objects get fatter, small gaps close, thin breaks join, tiny dark holes fill. A 3×3 all-1 SE expands a 3×3 block to 5×5.
Answer:
Opening: \(I \circ SE = (I \ominus SE) \oplus SE\) — Erosion then Dilation. Removes small bright dots/noise, keeps object size.
Closing: \(I \bullet SE = (I \oplus SE) \ominus SE\) — Dilation then Erosion. Fills small dark holes/gaps, keeps object size.
Answer:
White Top-Hat: \(WTH = I - (I \circ SE)\) — extracts small bright details, corrects uneven illumination.
Black Top-Hat: \(BTH = (I \bullet SE) - I\) — extracts small dark details/defects.
Gradient: \(G = (I \oplus SE) - (I \ominus SE)\) — dilated minus eroded = boundary outline.
Answer:
1. Mean: \(g = \frac{1}{mn}\sum f(s,t)\) — plain average, blurs edges.
2. Gaussian: \(G(x,y)=\frac{1}{2\pi\sigma^2}e^{-(x^2+y^2)/2\sigma^2}\) — centre-weighted, e.g. \(\frac{1}{16}\begin{bmatrix}1&2&1\\2&4&2\\1&2&1\end{bmatrix}\).
3. Median: \(g = \text{median}\{f(s,t)\}\) — non-linear, best for salt & pepper.
4. Bilateral: spatial × intensity weights — denoises flat areas, preserves edges.
Answer:
\(G_x\) detects vertical edges, \(G_y\) horizontal edges. High \(G\) = strong edge; edge runs perpendicular to gradient direction \(\theta\).
Answer: Second-order derivative, responds to zero-crossings:
Differentiation amplifies high-frequency noise (2nd order worse than 1st) — so always smooth with Gaussian first: LoG (Laplacian of Gaussian).
Answer: Derivatives amplify noise — a noisy spike gives a huge false gradient. Smoothing (Gaussian) suppresses high-frequency noise while keeping true step edges, so detectors fire only on real boundaries. Pipeline: Smooth → Differentiate → Threshold magnitude.
Answer: 1st order (Sobel, Prewitt, Roberts) gives gradient magnitude — maxima mark edges, plus direction. 2nd order (Laplacian) gives zero-crossings — precise localisation, no direction, but very noise-sensitive. Exam rule: Sobel for noisy images, Laplacian/LoG for exact edge position after smoothing.
Answer: Additive noise; every pixel shifted by a normally distributed value:
Looks like uniform grain. Best removed by Gaussian/mean smoothing.
Answer: Impulse noise — random pixels forced to 0 (pepper) or max (salt):
Best filter = Median: sorting discards extreme 0/max outliers while keeping true edges. Mean would smear the dots into gray blur.
Answer: Poisson (photon-counting): variance = mean, \(\text{Var} = \lambda\); brighter pixels noisier in absolute terms; common in X-ray/low-light. Speckle (multiplicative): \(g = f \cdot \eta\); grain scales with intensity; common in SAR/ultrasound. Exam: Gaussian = additive, Speckle = multiplicative, S&P = impulse, Poisson = photon.
Answer: Mean: \(g=\frac{1}{mn}\sum f\) — uniform noise, but blurs edges. Gaussian: centre-weighted average — Gaussian noise + edge-preserving pre-smoothing. Median: middle of sorted values — salt & pepper, preserves edges. Rule: impulse → median; additive Gaussian → Gaussian/mean.
Answer: Filter strength follows local variance \(\sigma_L^2\) vs noise variance \(\sigma_\eta^2\):
Flat area (\(\sigma_L^2 \approx \sigma_\eta^2\)) → heavy averaging. Edge (\(\sigma_L^2 \gg \sigma_\eta^2\)) → keep pixel. Adaptive median additionally grows the window until non-impulse median found — kills dense salt & pepper.
Answer: Document black-on-white → Otsu/global (bimodal). Shadows → adaptive threshold. Tumor on uniform tissue → region growing. Multiple coloured objects → K-means/colour. Boundaries needed → edge-based (Canny). Check: lighting, #classes, noise, region-vs-boundary.
Answer: Segment in HSV (hue immune to lighting):
Answer:
Roberts (2×2): \(G_x=\begin{bmatrix}1&0\\0&-1\end{bmatrix}\), fast but noise-sensitive.
Prewitt (3×3): \(G_x=\begin{bmatrix}-1&0&1\\-1&0&1\\-1&0&1\end{bmatrix}\), uniform weights.
Sobel (3×3): centre row ×2 — best of the three under noise.
All: \(G=\sqrt{G_x^2+G_y^2}\).
Answer:
Eigenvalue view: both \(\lambda\) large = corner; one large = edge; both small = flat.
Answer: (1) Sobel \(I_x,I_y\); (2) products \(I_x^2,I_y^2,I_xI_y\); (3) Gaussian sum over window; (4) compute \(R\); (5) threshold \(R>T\); (6) non-max suppression (keep local max only). Rotation invariant (eigenvalues unchanged), NOT scale invariant (fix: SIFT/scale-space), fast, many responses per corner.
Answer:
Translation: \(\begin{bmatrix}x'\\y'\end{bmatrix}=\begin{bmatrix}x\\y\end{bmatrix}+\begin{bmatrix}t_x\\t_y\end{bmatrix}\) (no 2×2 form!)
Rotation: \(\begin{bmatrix}x'\\y'\end{bmatrix}=\begin{bmatrix}\cos\theta&-\sin\theta\\\sin\theta&\cos\theta\end{bmatrix}\begin{bmatrix}x\\y\end{bmatrix}\)
Scaling: \(\begin{bmatrix}x'\\y'\end{bmatrix}=\begin{bmatrix}s_x&0\\0&s_y\end{bmatrix}\begin{bmatrix}x\\y\end{bmatrix}\)
Shearing: \(\begin{bmatrix}1&sh_x\\sh_y&1\end{bmatrix}\) — square → parallelogram
Reflection: \(\begin{bmatrix}-1&0\\0&1\end{bmatrix}\) — mirror, \(\det=-1\)
Answer: Translation is an addition, not a 2×2 multiplication. Promoting \((x,y) \to (x,y,1)\) turns ALL transforms into uniform 3×3 multiplications, so composites become single matrix products:
Answer: Matrices apply right to left: \(\mathbf{x'} = T \cdot R \cdot S \cdot \mathbf{x}\) means Scale first, then Rotate, then Translate. Order matters: \(T\cdot R \neq R\cdot T\) in general. Exam trap: translating then rotating ≠ rotating then translating.
Answer:
(1,0) → (0,1). Memorise: 90° CCW maps \((x,y)\to(-y,x)\).
Answer: Rotation preserves orientation, \(\det(R)=+1\). Reflection flips orientation (mirror image), \(\det(F)=-1\), and cannot be achieved by any rotation. Both preserve distances (rigid), but only rotation is physically reachable by turning the image.
Answer: Input (raw features) → Hidden (\(z=\sum w_ix_i+b\), \(a=f(z)\), feature extraction) → Output (sigmoid/binary, softmax/multi-class, linear/regression). Without non-linear activations, stacked linear layers collapse into one linear map — the net could never learn complex patterns.
Answer:
Sigmoid: \(\sigma(z)=\frac{1}{1+e^{-z}}\), (0,1) — binary output.
Tanh: \(\tanh(z)=\frac{e^z-e^{-z}}{e^z+e^{-z}}\), (−1,1) — zero-centred hidden.
ReLU: \(\max(0,z)\) — default hidden layer.
Leaky ReLU: \(\max(0.01z,z)\) — kills no dead neurons.
Softmax: \(S(z_i)=\frac{e^{z_i}}{\sum_j e^{z_j}}\) — multi-class output (sums to 1).
Answer: Forward: \(h_j=f(\sum_i w_{ji}x_i+b_j)\), \(\hat{y}=g(\sum_j v_jh_j+b_o)\), \(L=\frac{1}{2}(\hat{y}-y)^2\). Backward (chain rule):
Compute error at output, propagate backwards layer by layer, update every weight.
Answer: Products of many layer-derivatives: vanishing (sigmoid \(f'\le0.25\) compounds → 0, early layers freeze) vs exploding (large weights → ∞, NaN loss). Fixes: ReLU, BatchNorm, residual links, good init, gradient clipping, moderate LR.
Answer:
MSE (regression): \(L=\frac{1}{N}\sum(\hat{y}-y)^2\).
Cross-Entropy (classification): \(L=-\sum y\log\hat{y}\).
CE + softmax/sigmoid gives clean gradients for class probabilities; MSE for continuous targets.
Answer:
Momentum smooths zigzags and accelerates through ravines. SGD generalises well but needs LR tuning.
Answer: Momentum (1st moment) + adaptive LR (2nd moment), with bias correction:
Defaults \(\beta_1{=}0.9,\beta_2{=}0.999,\epsilon{=}10^{-8}\). Default choice: fast, per-parameter LR, works on sparse/non-stationary problems.
Answer: Too large → overshoot, oscillation, divergence. Too small → slow crawl, stuck in sharp minima. Fix with schedules: step decay, exponential decay, cosine annealing; warmup for transformers.
Answer: Overfit: train loss low, val loss high (memorised noise) — fix: more data, augmentation, dropout, weight decay, early stopping. Underfit: both losses high (model too weak) — fix: bigger model, more epochs, higher LR, better features.
Answer: Conv (local kernels, weight sharing) → ReLU → Pooling (max/avg, downsample + invariance) → FC + softmax. Hierarchy: edges → textures → objects.
Dilated (\(r>1\)) conv widens receptive field with same weights — used in segmentation to keep resolution.
Answer: (1) Split \(H{\times}W{\times}C\) image into \(P{\times}P\) patches: \(N=\frac{HW}{P^2}\) (e.g. 224/16 → 196). (2) Flatten + linear-project each to \(D\)-dim. (3) Prepend learnable [CLS] token. (4) Add positional embeddings. (5) \(L\) Transformer encoder layers. (6) [CLS] output → MLP head → class.
Answer:
Each patch (Query) scores all patches (Keys); scores weight the Values. \(\sqrt{d_k}\) stops softmax saturation. Multi-head = several such attentions in parallel, concatenated + projected.
Answer: [CLS] = learnable token with no image content; after attending to all patches its vector summarises the image for classification. Positional encoding (learnable in ViT) restores spatial order destroyed by flattening — without it, shuffling patches would not change the output.
Answer: Pre-norm + residuals around each sub-layer:
MSA mixes information across patches (global context); MLP (GELU, hidden 4×\(D\)) processes each patch independently; residuals + LayerNorm stabilise deep stacks.
Answer: CNN: local receptive field, translation-invariance baked in, data-efficient. ViT: global attention from layer 1, almost no inductive bias, needs large data/pretraining, wins at scale. Exam line: "ViT = patches + positions + Transformer; no convolution; global context from the start."