110 Computer Vision Interview Questions and Answers (2026)

Computer Vision now runs in production everywhere: checkout cameras, medical scans, warehouse robots, document pipelines. Interviewers know this, so they've stopped settling for "I fine-tuned a ResNet once" and now probe whether you understand why a BGR input tanks accuracy or why mAP drops on small objects. Walk in shaky on the fundamentals and it shows within five minutes.
This guide gives you 110 questions with concise, interview-ready answers, plus code where it actually helps. They're ordered Junior → Mid → Senior, so you start with image representation and preprocessing and build up to detection losses, vision transformers, VLMs, tracking and deployment. Work through them in order and you'll answer the follow-up questions with confidence, not just the opener.
Q1.Why do we normalize input images using the pretraining dataset's mean and standard deviation?
A pretrained network's weights were learned on inputs with a specific distribution; normalizing new images with the same per-channel mean and std reproduces that distribution, so the learned filters, biases, and normalization statistics behave as they did during pretraining.
What the transform does:
Per channel:
x' = (x/255 - mean) / std, giving roughly zero-mean, unit-variance inputs.ImageNet values: mean
[0.485, 0.456, 0.406], std[0.229, 0.224, 0.225](RGB order).
Why match the pretraining statistics:
First-layer filters and biases are calibrated to that input range; a shifted distribution changes activations in every subsequent layer (a self-inflicted domain shift).
BatchNorm running statistics were computed on normalized data; at inference they are frozen, so mismatched inputs are mis-normalized.
Fine-tuning starts from a good point instead of first having to re-adapt to a new input scale.
Why normalize at all: Zero-centred, similarly scaled inputs give better-conditioned gradients and faster, more stable optimization.
Practical notes:
Use the dataset's own stats only when training from scratch; for transfer learning, use the stats the backbone was trained with.
Some models use different conventions (e.g. CLIP's own mean/std, or scaling to
[-1, 1]); always check the model card.
Q2.What is the difference between RGB, BGR, and HSV colour spaces?
RGB and BGR hold the same red/green/blue intensities in different channel orders, while HSV is a different representation that separates colour (hue), purity (saturation), and brightness (value).
RGB: Additive model matching camera sensors and displays; standard in PIL, matplotlib, and most deep learning pretrained models.
BGR:
Same data, channels reversed; OpenCV's default (
cv2.imreadreturns BGR) for historical reasons.Convert with
cv2.cvtColor(img, cv2.COLOR_BGR2RGB)orimg[..., ::-1].
HSV:
Hue: colour angle on a wheel (0 to 360°; OpenCV stores 0 to 179 for 8-bit).
Saturation: how pure vs. greyish the colour is; Value: brightness.
Nonlinear transform of RGB; hue is circular, so red wraps around both ends.
When to use which:
HSV for classical colour segmentation/thresholding (e.g.
cv2.inRange): hue is fairly robust to lighting changes, unlike raw RGB values.RGB for CNNs (match the pretraining format); HSV is also used for colour-jitter augmentation.
Q3.Why do computer vision models often fail when trained on RGB images but evaluated on BGR inputs?
Swapping RGB to BGR silently exchanges the red and blue channels, so the network receives inputs from a distribution it never saw: first-layer filters tuned to specific channels respond to the wrong colours, and features downstream degrade.
Why the model is sensitive:
Conv filters have separate weights per input channel; colour-tuned filters (skin, sky, foliage) fire incorrectly when R and B are swapped.
Per-channel normalization is also applied with the wrong mean/std, adding a further shift.
BatchNorm statistics no longer match, so activations drift through the network.
How it shows up: Not a crash: a silent accuracy drop, often worst on colour-dependent classes (e.g. fruit, traffic lights); shape-driven predictions may still look fine, hiding the bug.
Common cause: Training with PIL/torchvision (RGB) but deploying with OpenCV
cv2.imread(BGR), or vice versa.Prevention:
Share one preprocessing function between training and serving; convert explicitly with
cv2.cvtColor.Sanity-check by visualizing the tensor fed to the model and comparing outputs on a reference image.
Q4.What is the difference between 8-bit and 16-bit depth in image representation?
Bit depth is the number of bits per channel per pixel: 8-bit gives 256 intensity levels, 16-bit gives 65,536, so 16-bit captures finer gradations and more dynamic range at twice the memory.
8-bit (
uint8, 0 to 255):Standard for JPEG, webcams, and most datasets; enough for display and typical CNN inputs.
Coarse steps can cause banding in smooth gradients and clip detail in shadows/highlights.
16-bit (
uint16, 0 to 65535):Used in medical imaging (DICOM), depth sensors (often millimetres), scientific/astronomy, RAW and HDR workflows (PNG, TIFF).
Preserves subtle intensity differences and survives heavy editing (contrast stretching) without posterization.
Practical pitfalls:
Dividing a 16-bit image by 255 instead of 65535 (or the sensor's real max) gives wildly wrong values.
Some loaders silently downcast:
cv2.imreadneedscv2.IMREAD_UNCHANGEDto keep 16-bit.Sensors often use 10/12/14 bits stored in 16-bit containers, so the true range may be smaller than 65535.
Q5.What is the difference between nearest-neighbour and bilinear interpolation when resizing images?
Nearest-neighbour copies the value of the closest source pixel, while bilinear computes a distance-weighted average of the 4 surrounding pixels: nearest is fast and preserves exact values but looks blocky; bilinear is smoother but blends values.
Nearest-neighbour:
Each output pixel maps back to a fractional source location and takes the nearest pixel's value.
Produces jagged edges and blockiness on upscaling; aliasing on downscaling.
Never creates new values: the right choice for segmentation masks and label maps, where blending class IDs 1 and 3 into 2 would be nonsense.
Bilinear:
Linear interpolation along x, then along y, over the 2×2 neighbourhood.
Smoother results; slightly blurs sharp edges; a bit more compute.
Default for natural images fed to CNNs.
Related details:
For strong downscaling, area averaging (
cv2.INTER_AREA) or antialiasing reduces aliasing better than either.Bicubic (4×4 neighbourhood) is sharper for upscaling.
Keep the same method (and library) between training and inference to avoid subtle distribution shift.
Q6.What happens to model predictions if 8-bit pixel values in [0, 255] are passed to a network trained on normalized floats in [0, 1]?
The inputs are 255× larger than anything seen in training, so activations blow up far outside the learned range and predictions become garbage: typically one confidently wrong class or near-constant outputs, with no error raised.
What happens inside:
First-layer pre-activations scale by ~255 (the bias no longer balances the weights), so ReLUs saturate on and the signal pattern differs from training.
Frozen BatchNorm statistics in eval mode can't correct it; magnitudes stay huge downstream.
Softmax over huge logits becomes near one-hot: the model looks extremely confident while being wrong.
Why it's dangerous:
Shapes and dtypes may still pass (especially after a cast to float), so the bug is silent.
Possible overflow to
inf/NaNin fp16 inference.
The reverse mistake (dividing twice) also fails: inputs near zero give washed-out, low-contrast features.
Prevention: One shared preprocessing function; assert value range (e.g.
x.max() <= 1.0) before inference; regression-test against a reference image's known output.
Q7.What is the difference between morphological erosion and dilation?
Erosion shrinks foreground (white) regions by keeping a pixel only if the whole structuring element fits inside the foreground; dilation grows them by turning a pixel on if the structuring element touches any foreground. They are duals and are combined into opening and closing.
Erosion:
Binary: pixel stays 1 only if all pixels under the kernel are 1; greyscale: minimum filter.
Removes small noise specks, thins objects, separates touching objects.
Dilation:
Binary: pixel becomes 1 if any pixel under the kernel is 1; greyscale: maximum filter.
Fills small holes and gaps, thickens objects, joins broken parts.
Combinations:
Opening = erosion then dilation: removes small bright noise while roughly keeping object size.
Closing = dilation then erosion: fills small dark holes and gaps.
Morphological gradient = dilation minus erosion: gives object outlines.
Control knobs: kernel size/shape (
cv2.getStructuringElementwith rect, ellipse, cross) and iterations.
Q8.How does histogram equalisation improve image contrast?
Histogram equalisation remaps pixel intensities through the image's cumulative distribution function (CDF), so that frequently occurring intensity ranges get stretched across more of the output range. Narrow, crowded histograms become roughly uniform, which increases global contrast.
The mapping:
Compute the histogram of intensities (e.g. 256 bins for 8-bit).
Normalise it into a PDF and accumulate it into a CDF.
Map each level:
s = round((L-1) * (CDF(r) - CDF_min) / (N - CDF_min)), where L is the number of levels and N is the pixel count.
Why it boosts contrast:
The CDF is steep where many pixels share similar values, so those dense ranges are spread far apart in the output.
Sparse ranges are compressed. Because the CDF is monotonic, intensity ordering is preserved.
Limitations:
It is a global method: it can amplify noise in flat regions and wash out local detail.
It can produce unnatural results. On colour images, apply it to a luminance channel (e.g. Y in YCrCb, or V in HSV), not to each RGB channel separately.
CLAHE (Contrast Limited Adaptive HE):
Equalises small tiles and clips each histogram at a limit, which caps noise amplification.
Blends neighbouring tiles with bilinear interpolation to avoid visible seams.
In OpenCV:
cv2.equalizeHistfor global HE vscv2.createCLAHE.
Q9.How does the Sobel operator compute edge gradients in an image?
Sobel convolves the image with two 3×3 kernels that approximate the horizontal and vertical intensity derivatives, each combined with smoothing in the perpendicular direction. The two responses give a gradient vector at each pixel, from which you get edge strength (magnitude) and edge orientation.
The kernels:
Gx = [[-1,0,1],[-2,0,2],[-1,0,1]]responds to vertical edges (change along x).Gyis its transpose and responds to horizontal edges.
Why this structure:
Each kernel is separable: a central difference
[-1,0,1]times a smoothing filter[1,2,1].The smoothing makes it less noise-sensitive than a raw finite difference.
The 2 weight emphasises the centre row or column.
Combining the responses:
Magnitude:
sqrt(Gx² + Gy²), often approximated by|Gx| + |Gy|.Direction:
atan2(Gy, Gx), which is perpendicular to the edge.
Practical notes:
Use a signed output type (e.g.
cv2.CV_64Fincv2.Sobel). Otherwise negative gradients are clipped and you lose dark-to-light versus light-to-dark transitions.Sobel produces thick edges. Thinning them and making binary decisions needs further steps, such as non-maximum suppression and thresholding in Canny.
Q10.How does a Gaussian blur filter reduce high-frequency image noise?
A Gaussian blur replaces each pixel with a weighted average of its neighbours, using weights from a 2D Gaussian. Averaging cancels out uncorrelated pixel-to-pixel fluctuations. In frequency terms, a Gaussian is a low-pass filter whose frequency response is also a Gaussian, so high-frequency content (noise, but also fine detail) is smoothly attenuated.
Spatial view:
Kernel:
G(x,y) ∝ exp(-(x²+y²)/(2σ²)), normalised to sum to 1 so overall brightness is preserved.Nearby pixels count more than distant ones, which blurs less harshly than a box filter.
Averaging n independent noise samples reduces the noise variance roughly by a factor of n.
Frequency view:
The Fourier transform of a Gaussian is a Gaussian, so attenuation increases smoothly with frequency.
It has no ringing, unlike the sinc-shaped response of a box filter or the sharp cutoff of an ideal low-pass filter.
A larger spatial σ gives a narrower frequency passband, i.e. more smoothing.
Useful properties:
Separable: a 2D blur equals two 1D passes, reducing cost per pixel from O(k²) to O(2k).
Kernel size rule of thumb: about 6σ+1, since this captures roughly ±3σ.
Commonly used as pre-smoothing before differentiation (Canny, Laplacian of Gaussian).
Trade-off:
Edges are high-frequency too, so they get blurred as well.
Edge-preserving alternatives: bilateral filter, non-local means.
For impulse (salt-and-pepper) noise, a median filter is better.
Q11.Why is a median filter more effective than a mean filter at removing salt-and-pepper noise?
Salt-and-pepper noise consists of isolated extreme outliers (0 or 255). A mean filter folds those outliers into the average, so it smears them into grey blotches. A median filter picks the middle value of the sorted neighbourhood, so a few extreme pixels are simply ignored.
Mean filter behaviour:
It is linear: one 255 pixel in a 3×3 window of 50s shifts the mean to about 72. The outlier is spread over 9 pixels rather than removed.
It also blurs edges, because it averages across them.
Median filter behaviour:
It is non-linear and robust: the median has a 50% breakdown point. As long as fewer than half the window pixels are corrupted, the output is a genuine uncorrupted value.
It preserves step edges well, since the output is always an existing value from one side of the edge rather than an in-between blend.
Limitations:
Fails at high noise density, when corrupted pixels make up half the window or more. Adaptive median filters, which grow the window, address this.
Removes thin lines and corners smaller than about half the window.
More expensive than a mean filter (sorting or histogram-based selection).
Less effective than Gaussian smoothing on Gaussian noise.
OpenCV:
cv2.medianBlur(img, 3)vscv2.blur(img, (3,3)).
Q12.What is the conceptual difference between a keypoint detector and a feature descriptor?
A detector answers where: it finds repeatable, distinctive locations (and often their scale and orientation) that can be re-found under viewpoint or lighting changes. A descriptor answers what it looks like: it encodes the local patch around each keypoint as a vector that can be compared across images for matching.
Keypoint detector:
Output: (x, y), plus optional scale, orientation, and response strength.
Goal: repeatability, i.e. the same physical point is detected across views.
Examples: Harris and Shi-Tomasi corners, FAST, DoG (from SIFT), the Hessian detector (from SURF).
Feature descriptor:
Output: a fixed-length vector per keypoint, for example 128-D float for SIFT or a 256-bit binary string for ORB/BRIEF.
Goal: distinctiveness plus invariance (rotation, scale, illumination), so correct matches are close and wrong ones far apart.
Compared with L2 distance for float descriptors, or Hamming distance for binary ones.
How they interact:
Invariance often comes from the detector: the descriptor is computed on a patch normalised by the detected scale and orientation.
They can be mixed and matched, e.g. FAST keypoints with BRIEF descriptors (which is essentially ORB).
Some methods do both jointly: SIFT, ORB, and learned ones like SuperPoint.
Typical pipeline: detect, describe, match (with a ratio test), then apply geometric verification with
RANSAC.
Q13.What is test-time augmentation?
Test-time augmentation (TTA) runs the model on several augmented copies of each test input and aggregates the predictions. Averaging out the model's sensitivity to small transformations usually gives a modest accuracy boost, at the cost of more inference compute.
How it works:
Create variants of the input, such as horizontal flips, multi-scale resizes and crops.
Run inference on each variant.
Invert any geometric transform on the outputs. For example, un-flip segmentation masks and box coordinates.
Aggregate the results.
Aggregation by task:
Classification: average softmax probabilities or logits.
Segmentation: average the per-pixel probabilities after mapping them back.
Detection: merge boxes with NMS or Weighted Boxes Fusion.
Trade-offs:
Inference cost grows by roughly a factor of k for k augmentations, which is often unacceptable for real-time systems.
Only use transforms the model saw during training and that preserve labels. For example, avoid vertical flips for text or digits.
It also gives a cheap uncertainty signal through the disagreement between variants.
Q14.What is the difference between photometric and geometric data augmentations?
Photometric augmentations change pixel values (color, brightness, noise) but leave positions unchanged. Geometric augmentations move pixels spatially (flip, rotate, crop, scale). Only geometric ones require transforming the labels too.
Photometric:
Examples: brightness and contrast, hue and saturation jitter, gamma, blur, Gaussian noise, JPEG compression.
They simulate lighting, sensor and camera variation.
Boxes, masks and keypoints stay unchanged.
Geometric:
Examples: flips, rotation, scaling, translation, cropping, affine and perspective warps.
They simulate viewpoint, pose and object-size variation.
Labels must be transformed with the same parameters: boxes, masks, keypoints and sometimes keypoint identities (left and right swap on a flip).
Choosing them:
They must preserve labels. Color jitter is a bad choice when color defines the class (traffic lights), and rotation is a bad choice for orientation-dependent digits like 6 and 9.
Libraries such as
Albumentationsandtorchvision.transforms.v2apply geometric transforms to targets automatically.
Q15.How must ground-truth bounding box coordinates be adjusted when an image undergoes a random crop?
Shift each box by the crop's top-left offset, clip it to the crop bounds, and drop boxes that end up empty or mostly cut off.
Steps, for a crop at (cx, cy) of size (cw, ch) and a box (x1, y1, x2, y2):
Translate: subtract cx from x1 and x2, and cy from y1 and y2.
Clip: limit x coordinates to [0, cw] and y coordinates to [0, ch].
Filter: discard boxes with zero width or height, or whose remaining visible area is below a threshold (e.g. under 25 to 50% of the original). Drop their class labels as well.
Rescale if the crop is resized to the network input size: multiply by out_w / cw and out_h / ch.
Gotchas:
Normalized formats such as YOLO's cx, cy, w, h must be renormalized by the crop size, not the original image size.
Heavily truncated objects can produce misleading labels. SSD-style crops sample crops that meet a minimum IoU with the objects.
Masks and keypoints must be cropped consistently with the boxes.
Q16.How must bounding box coordinates be adjusted when applying a random horizontal flip?
Mirror the x coordinates about the image width and swap them so that min stays min: new_x1 = W − x2 and new_x2 = W − x1. The y coordinates are unchanged.
Corner format (x1, y1, x2, y2):
Use (W − x2, y1, W − x1, y2).
Simply computing W − x1 and W − x2 in place without swapping produces x1 > x2, an invalid box with negative width.
Center format (cx, cy, w, h):
Pixels: cx becomes W − cx, and the other values stay the same.
Normalized, as in YOLO: cx becomes 1 − cx.
Pixel convention: if coordinates are pixel indices rather than continuous edges, use W − 1 − x instead of W − x.
Related labels:
Masks are flipped the same way.
Keypoints flip their x, and left/right identities must be swapped (left eye becomes right eye).
Direction-dependent classes, such as left-turn signs, may need relabeling or should not be flipped at all.
Q17.How does standard non-maximum suppression work in object detection?
NMS removes duplicate detections of the same object: it greedily keeps the highest-scoring box and suppresses any remaining box that overlaps it by more than an IoU threshold, repeating until no boxes are left.
Algorithm (run per class):
Drop boxes below a confidence threshold.
Sort the rest by score, descending.
Take the top box, add it to the output.
Compute IoU with every remaining box; discard those with IoU > threshold (commonly 0.5).
Repeat from step 3 until the list is empty.
Why it's needed: detectors emit many overlapping predictions (anchors/grid cells) for one object.
Limitations:
Hard threshold: overlapping true objects (crowds) can be suppressed; too high a threshold leaves duplicates.
Greedy and not differentiable; worst case O(n²).
Variants: Soft-NMS (decay scores instead of deleting), DIoU-NMS, and NMS-free detectors like DETR.
Q18.What is the difference between Pascal VOC and COCO bounding box coordinate formats?
Pascal VOC stores a box as its two corners [x_min, y_min, x_max, y_max], while COCO stores the top-left corner plus size [x_min, y_min, width, height]; both are in absolute pixels.
Pascal VOC:
Corner format, stored in per-image XML files (
<xmin>,<ymin>,<xmax>,<ymax>).Original annotations are 1-based integer pixel indices.
COCO: Corner + size format in a single JSON file under
annotations[i]["bbox"], with float values (0-based).Conversion:
VOC to COCO:
w = x_max - x_min,h = y_max - y_min.COCO to VOC:
x_max = x_min + w,y_max = y_min + h.
Contrast with YOLO: normalized
[x_center, y_center, w, h]in [0, 1].Why it matters: mixing formats silently breaks IoU, augmentation, and mAP; a classic bug is treating width as x_max.
Q19.What is the purpose of anchor boxes in object detection?
Anchor boxes are predefined reference boxes of several sizes and aspect ratios tiled across the feature map; the detector predicts offsets and objectness relative to them instead of regressing boxes from scratch, which makes localization easier and lets one location detect multiple differently shaped objects.
How they work:
At each feature-map cell, k anchors (e.g. 3 scales × 3 ratios) are placed.
The head predicts class scores and offsets
(tx, ty, tw, th): center shift scaled by anchor size, and log-scale width/height.
Why they help:
Regressing small residuals from a good prior is more stable than predicting absolute coordinates.
Multiple shapes per location handle overlapping objects and varied aspect ratios (tall person vs. wide car).
They define training targets: anchors with high IoU to a ground-truth box are positives, low IoU are negatives.
Downsides:
Hyperparameters (scales, ratios) must suit the dataset; YOLOv2+ picks them via k-means on training boxes.
Huge numbers of mostly negative anchors cause class imbalance (addressed by focal loss) and need NMS.
Anchor-free detectors (FCOS, CenterNet, YOLOv8) predict boxes from points directly and avoid this tuning.
Q20.What is the main trade-off between single-stage detectors like YOLO and two-stage detectors like Faster R-CNN?
It's speed vs. accuracy: single-stage detectors predict classes and boxes in one dense pass, making them fast enough for real-time; two-stage detectors first propose regions then refine each one, traditionally giving better localization and small-object accuracy at higher latency.
Two-stage (Faster R-CNN):
An RPN proposes ~hundreds to thousands of RoIs; RoI pooling/align crops features and a second head classifies and refines each.
The proposal stage filters out most background, so the second head trains on a balanced sample: more precise boxes.
Per-RoI computation makes it slower; easily extended (Mask R-CNN).
Single-stage (YOLO, SSD, RetinaNet):
Dense predictions on a grid/anchors in one forward pass; simple and fast, good for edge deployment.
Faces extreme foreground/background imbalance; historically weaker on small or crowded objects.
The gap has narrowed:
Focal loss (RetinaNet), FPNs, and better training recipes let modern one-stage models match or beat two-stage accuracy.
Choose by constraints: latency budget and hardware vs. need for maximum precision or instance masks.
Q21.How is Intersection over Union calculated between two bounding boxes?
IoU is the area of overlap divided by the area of union. Compute the intersection rectangle from the max of the top-left corners and the min of the bottom-right corners, clamp it at zero if the boxes don't overlap, and divide by the sum of both areas minus the intersection.
Steps (boxes in
(x1, y1, x2, y2)format):Intersection corners:
ix1 = max(a.x1, b.x1),iy1 = max(a.y1, b.y1),ix2 = min(a.x2, b.x2),iy2 = min(a.y2, b.y2).Intersection area:
max(0, ix2 - ix1) * max(0, iy2 - iy1). The clamp handles non-overlapping boxes.Union:
area_a + area_b - inter. Subtracting the intersection avoids double counting it.IoU = inter / union, which lies in [0, 1].
Gotchas:
Convert
(cx, cy, w, h)or(x, y, w, h)boxes to corner format first.Add a small epsilon to the denominator to avoid dividing by zero on degenerate boxes.
Some legacy code (e.g., Pascal VOC) uses inclusive pixel coordinates and adds +1 to widths and heights.
Vectorize it for N×M pairwise IoU using broadcasting. This is used in NMS and anchor matching.
Q22.What defines a true positive detection under an IoU threshold of 0.5?
A prediction is a true positive at IoU 0.5 when it has the correct class, overlaps a ground-truth box with IoU ≥ 0.5, and that ground-truth box has not already been claimed by a higher-confidence prediction. If it fails any of these, it is a false positive.
IoU condition:
IoU = area(pred ∩ gt) / area(pred ∪ gt). It must reach 0.5 (COCO uses ≥; the original VOC code used strictly >).
0.5 is lenient: a box can be noticeably shifted or mis-sized and still pass.
Class condition: Matching is done per class. A well-placed box with the wrong label is a FP for its predicted class, and the object stays a FN for its true class.
One-to-one greedy matching:
Sort the predictions by confidence, highest first.
Match each prediction to the unmatched GT box with the highest IoU, as long as that IoU is above the threshold.
Any later prediction on an already-matched GT is a duplicate, so it counts as a FP.
Special cases:
GT boxes flagged
difficult(VOC) oriscrowd(COCO) are ignored. Detections matched to them count as neither TP nor FP.GT boxes that end up unmatched are false negatives, and they lower recall.
Q23.What is the conceptual difference between semantic, instance, and panoptic segmentation?
Semantic segmentation labels every pixel with a class but does not separate individual objects. Instance segmentation separates individual objects (masks per instance) but usually covers only countable "things". Panoptic segmentation unifies both: every pixel gets a class and, for things, an instance ID, with no overlaps.
Semantic segmentation:
Output: one class map (H×W); two adjacent cars merge into one "car" region.
Covers both things and "stuff" (sky, road, grass).
Models: FCN, U-Net, DeepLab. Metric: mIoU.
Instance segmentation:
Output: a set of (mask, class, score) per object; it distinguishes car #1 from car #2.
Masks may overlap, and background or stuff is ignored.
Models: Mask R-CNN, YOLACT. Metric: mask AP.
Panoptic segmentation:
Output: each pixel gets a (class, instance_id) pair; stuff classes have no instance ID.
Non-overlapping, complete coverage of the image.
Models: Panoptic FPN, Mask2Former.
Metric: Panoptic Quality, PQ = SQ (segmentation quality) × RQ (recognition quality), with segments matched at IoU > 0.5.
Q24.What is the role of skip connections in U-Net?
Skip connections in U-Net copy encoder feature maps directly to the decoder stage of the same resolution, so the decoder can recover the fine spatial detail lost during downsampling while still using the deep, semantic features from the bottleneck.
The problem they solve:
Pooling and strided convs enlarge the receptive field but discard precise location (edges, thin structures).
Upsampling from the bottleneck alone gives blurry, coarse boundaries.
How they work:
Encoder features at level
iare concatenated channel-wise with the upsampled decoder features at leveli, then fused by convolutions.The original paper used unpadded convs, so encoder maps were center-cropped to match; modern versions use padding and skip cropping.
What they give you:
Localization ("where") from shallow layers combined with semantics ("what") from deep layers.
Shorter gradient paths to early layers, which eases training and helps with small datasets (e.g. medical imaging).
Concatenation vs addition: U-Net concatenates (keeps both feature sets, lets the decoder learn how to mix them); FCN and ResNet-style skips sum features, which is cheaper but less expressive.
Q25.How is mean IoU computed across multiple classes in semantic segmentation?
Compute IoU separately for each class as TP / (TP + FP + FN), usually accumulated over the whole dataset, then take the unweighted average over classes. Every class counts equally, regardless of how many pixels it covers.
Build a confusion matrix:
Accumulate a C×C matrix (rows = ground truth, cols = prediction) over all pixels of all images.
For class c: TP = diagonal entry, FP = column sum minus TP, FN = row sum minus TP.
IoU_c = TP / (TP + FP + FN); mIoU = mean over classes.
Dataset-level vs per-image: Standard benchmarks (PASCAL VOC, Cityscapes) accumulate counts over the full dataset before dividing; averaging per-image IoUs gives a different, noisier number.
Edge cases:
Classes with zero union (absent in both GT and prediction) are excluded from the mean, not counted as 0 or 1.
Pixels with an ignore label (often
255) are dropped before counting.
Variant: frequency-weighted IoU weights each class by its pixel frequency, which reintroduces bias toward large classes.
Q26.How does a Vision Transformer turn a 2D image into a sequence of input tokens?
A ViT turns an image into tokens in three steps:
Cut the image into non-overlapping fixed-size patches.
Flatten each patch and linearly project it to the model width D.
Prepend a learnable
[CLS]token and add positional embeddings.
Each patch then behaves like a "word" in an NLP transformer.
Patchify:
An H x W x C image with patch size P gives N = HW/P² patches. For example, 224x224 with P=16 gives 14x14 = 196 tokens.
Larger P means fewer tokens (cheaper, coarser). Smaller P means more tokens (quadratic attention cost).
Linear patch embedding:
Each patch is flattened to a P²·C vector and multiplied by a shared matrix E of shape (P²·C) x D.
In practice this is implemented as a
Conv2dwith kernel = stride = P.
Add a class token: A learnable
[CLS]vector is prepended, giving N+1 tokens. Its final state feeds the classification head.Add positional embeddings:
Self-attention is permutation-invariant, so learnable 1D position embeddings of shape (N+1) x D are added to restore spatial order.
The model learns 2D structure from these on its own: the original ViT found 2D-aware embeddings gave no real gain.
Q27.What is optical flow?
Optical flow is the per-pixel 2D displacement field (u, v) describing how brightness patterns appear to move between two consecutive frames. It estimates image-plane motion caused by object and/or camera movement.
Core constraint: brightness constancy:
Assume I(x, y, t) = I(x+u, y+v, t+1).
Linearizing gives the optical flow equation Ixu + Iyv + It = 0.
That is one equation with two unknowns per pixel: the aperture problem. Only motion along the gradient is observable locally.
Resolving the ambiguity requires extra assumptions:
Lucas-Kanade: constant flow within a local window (sparse, local).
Horn-Schunck: global smoothness regularization (dense).
Sparse vs dense:
Sparse: flow at feature points (
cv2.calcOpticalFlowPyrLK).Dense: flow at every pixel (
cv2.calcOpticalFlowFarneback, or deep models like FlowNet and RAFT).
Apparent motion vs true motion:
Flow is not identical to the projected 3D motion field.
A rotating uniform sphere shows no flow, while a lighting change shows flow with no motion.
Uses:
Video stabilization and frame interpolation.
Action recognition (two-stream networks).
Tracking, visual odometry, and motion segmentation.
Q28.Why is letterboxing preferred over direct resizing for object detection inputs?
Letterboxing scales the image uniformly to fit the target size and pads the remainder, preserving aspect ratio; direct resizing stretches the image, distorting object shapes the detector learned and making boxes harder to predict and map back.
Problem with direct resizing:
Non-uniform scaling squashes or stretches objects (a person becomes wide), shifting them away from the shapes and anchor aspect ratios seen in training.
Distortion varies with each image's original aspect ratio, adding inconsistency.
How letterboxing works:
Scale =
min(target_w / w, target_h / h); resize both sides by it.Pad the shorter side with a constant (YOLO uses grey 114) to reach the target size.
After inference, subtract the padding offset and divide by the scale to map boxes to original coordinates.
Benefits:
Geometry preserved, so predictions are more accurate and box coordinates invert exactly.
Fixed input size for batching; small objects aren't further squeezed along one axis.
Trade-offs:
Padding wastes compute and lowers effective resolution; YOLO's "rect"/minimal padding (pad to a stride multiple) mitigates this.
Must match training: a model trained on stretched images may perform worse with letterboxing, and vice versa.
Q29.When would you choose a classical image processing technique over a deep learning model?
Choose classical techniques when the problem is well-constrained and can be described by explicit rules (controlled lighting, known geometry), when data is scarce, or when compute, latency, interpretability, or certification requirements rule out a neural network. Choose deep learning when appearance varies too much to hand-engineer and you have data to learn from.
Controlled environments:
Industrial inspection, barcode or fiducial reading, measurement under fixed lighting and camera pose.
Thresholding, morphology, template matching, or contours often reach near-perfect accuracy here.
Little or no labelled data:
Classical methods need tuning, not training sets.
Rare defects may have too few examples to train a robust model.
Resource constraints:
Microcontrollers and low-power edge devices without a GPU or NPU.
Hard real-time limits at high frame rates.
Interpretability and guarantees:
Deterministic, debuggable behaviour with predictable failure modes.
Important in safety-critical or regulated settings (medical, automotive).
Geometry-driven problems: Camera calibration, homography or epipolar geometry, and pose estimation via
RANSACor PnP have exact mathematical solutions.Prefer deep learning when:
There is high intra-class variation, clutter, occlusion, or varying lighting.
The task is semantic (object detection, segmentation of natural scenes) and data is available.
Common in practice: hybrid pipelines:
Classical preprocessing (undistortion, ROI cropping) feeding a CNN.
A CNN detector followed by classical geometric verification or tracking.
Q30.How does Otsu's thresholding method determine the optimal binarization threshold?
Otsu's method tries every possible threshold on the grayscale histogram. It picks the one that best separates pixels into two classes (foreground and background): the threshold that maximises between-class variance, which is equivalent to minimising within-class variance.
Algorithm:
Compute the normalised histogram p(i) for levels 0 to L-1.
For each threshold t, compute the class weights ω₀(t), ω₁(t) (pixel fractions below and above t) and the class means μ₀(t), μ₁(t).
Between-class variance:
σ_B²(t) = ω₀ ω₁ (μ₀ − μ₁)².Choose
t* = argmax σ_B²(t).
Why maximising between-class variance works:
Total variance is fixed and equals within-class variance plus between-class variance.
So maximising separation between classes is the same as making each class as compact as possible.
Using cumulative sums, every threshold can be evaluated in O(L) total, which is very fast.
Assumptions and failure modes:
Works best on a bimodal histogram with reasonably separated peaks.
Struggles with very unequal class sizes (a small object on a large background), non-uniform illumination, or heavy noise.
Fixes: blur first, use local or adaptive thresholding, or apply multi-level Otsu for more than two classes.
OpenCV:
cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)returns the chosen threshold along with the binary image.
Q31.How does the Canny edge detector identify true edges while suppressing noise?
Canny is a multi-stage pipeline designed for good detection, accurate localisation, and a single response per edge. It smooths to suppress noise, computes gradients, thins edges to 1-pixel ridges, and then uses two thresholds with connectivity to keep strong edges plus weak edges that link to them.
1. Gaussian smoothing:
Removes high-frequency noise that would otherwise produce spurious gradients.
σ sets the trade-off: larger values suppress more noise but localise edges less precisely.
2. Gradient computation:
Sobel gives Gx and Gy, from which magnitude and direction are computed.
Direction is quantised to 0°, 45°, 90°, or 135°.
3. Non-maximum suppression:
A pixel is kept only if its magnitude is a local maximum along the gradient direction, compared with its two neighbours across the edge.
Turns thick gradient ridges into thin, 1-pixel-wide edges.
4. Double thresholding:
Above the high threshold: strong edge. Between low and high: weak candidate. Below low: discarded.
A typical high:low ratio is 2:1 to 3:1.
5. Edge tracking by hysteresis:
Weak pixels survive only if they connect (8-connectivity) to a strong edge.
Real edges, which form continuous contours, are kept even where contrast dips. Isolated noise responses, which are disconnected, are dropped.
OpenCV:
cv2.Canny(img, low, high). Its internal Sobel usesapertureSize, and smoothing is typically applied beforehand withcv2.GaussianBlur.
Q32.Why are SIFT features invariant to scale and rotation?
SIFT gets scale invariance by detecting keypoints as extrema across a scale space and describing each at its own detected scale. It gets rotation invariance by assigning each keypoint a dominant gradient orientation and expressing the descriptor relative to it.
Scale invariance: scale-space extrema:
The image is blurred with Gaussians of increasing sigma, grouped into octaves (downsampled by 2 each octave).
Adjacent levels are subtracted to form a Difference of Gaussians (DoG), which approximates the scale-normalized Laplacian of Gaussian.
A keypoint is a local max or min among its 26 neighbours in space and scale. Its characteristic scale moves with the object's size, so the same structure is found at a proportionally larger sigma when it is zoomed in.
The descriptor window is sized by that sigma, so it covers the same physical region regardless of image scale.
Rotation invariance: canonical orientation:
A 36-bin histogram of gradient orientations, weighted by magnitude and a Gaussian, is built around the keypoint.
The peak gives the dominant orientation. Additional keypoints are created for any other peak above 80% of the maximum.
Descriptor gradients are rotated relative to this angle, so a rotated image yields the same descriptor.
Descriptor robustness:
A 4×4 grid of 8-bin orientation histograms gives a 128-D vector. Pooling makes it tolerant to small shifts and deformations.
Normalizing, clipping at 0.2 and renormalizing adds robustness to illumination changes.
Limits: not invariant to large viewpoint (affine/perspective) changes; ASIFT-style methods address this.
Q33.How does the Histogram of Oriented Gradients (HOG) descriptor capture object shape?
HOG describes shape through the distribution of local edge directions. Gradient orientations are histogrammed in small cells and then contrast-normalized over blocks, so the descriptor encodes where edges are and which way they point, while ignoring exact pixel intensities.
Compute gradients:
Simple [-1, 0, 1] filters give gx and gy, from which magnitude and orientation are computed at each pixel.
Unsigned orientation (0 to 180°) is typical, so a dark-on-light edge matches a light-on-dark one.
Cell histograms:
The image is divided into cells (e.g. 8×8 pixels), each with a 9-bin orientation histogram.
Each pixel votes by gradient magnitude, with interpolation between neighbouring bins.
This summarizes the local contour direction while tolerating small shifts.
Block normalization:
Overlapping blocks of 2×2 cells are L2-normalized (or L2-Hys), which cancels lighting and contrast changes.
Because blocks overlap, each cell appears several times under different normalizations, which improves accuracy.
Concatenate:
All block vectors form one long, spatially ordered descriptor (3780-D for a 64×128 pedestrian window).
It is classically fed to a linear SVM, as in Dalal and Triggs.
Why it captures shape: object silhouettes such as a person's head, shoulders and legs produce characteristic edge-orientation patterns in fixed spatial positions.
Limits: not rotation- or scale-invariant; detection needs a sliding window over an image pyramid.
Q34.Why is RANSAC needed when estimating a homography from noisy feature matches?
Feature matching always produces some wrong correspondences (outliers). A least-squares homography fit, such as plain DLT, lets even a few bad matches pull the solution far off. RANSAC robustly finds the homography that most matches agree on and discards the outliers.
Why outliers appear:
Repetitive textures, ambiguous descriptors and occlusion all create them.
Points that do not lie on the plane, or that move independently, do not follow the homography.
Outlier rates of 30 to 60% are common, and least squares has a breakdown point of 0%.
RANSAC loop:
Randomly sample the minimal set: 4 correspondences, which give 8 DOF.
Compute H from those 4 points.
Count inliers, meaning matches whose reprojection error is below a threshold (a few pixels).
Keep the H with the most inliers, then refit on all inliers using least squares or Levenberg-Marquardt.
Number of iterations:
N = log(1 − p) / log(1 − w^4), where p is the desired confidence and w is the inlier ratio.
Minimal samples keep N small, because the chance of drawing an all-inlier sample is w^4.
In practice:
OpenCV:
cv2.findHomography(src, dst, cv2.RANSAC, 3.0)returns H and an inlier mask.Variants: MSAC, PROSAC, MAGSAC++ and
cv2.USAC_MAGSACare more robust or faster.A Lowe ratio test applied first reduces outliers.
Q35.What is the difference between Mixup and CutMix augmentations?
Both mix two training images and their labels. Mixup blends whole images pixel-wise, whereas CutMix pastes a rectangular patch of one image onto another. In both, labels are mixed in proportion to the blend weight or patch area.
Mixup:
x = λ·xA + (1 − λ)·xB and y = λ·yA + (1 − λ)·yB, with λ drawn from Beta(α, α).
It encourages linear behaviour between samples, which regularizes the model and improves calibration.
Drawback: it produces ghostly, unnatural overlays and blurs local features.
CutMix:
A random box from xB replaces the same region in xA.
λ is set to 1 minus the patch-area fraction, and labels are mixed with that λ.
Every pixel stays natural, and the model must recognize objects from partial views (like Cutout, but with no wasted pixels).
It often beats Mixup on localization and on ImageNet classification.
Drawback: the patch may miss the object entirely, which makes the label noisy.
Practical notes:
Both require soft-label cross-entropy.
They are commonly alternated within a batch, as in timm's
Mixupwithcutmix_alpha.For detection, variants such as Mosaic and box-level mixing are used instead, because box labels cannot be blended softly.
Q36.What is RandAugment?
RandAugment is an automated data-augmentation policy that replaces AutoAugment's expensive learned search. It applies N randomly chosen image operations to each image at a single shared magnitude M, so the whole policy space shrinks to two hyperparameters you can grid-search directly on the target task.
Motivation:
AutoAugment used reinforcement learning on a small proxy task to learn per-op probabilities and magnitudes. That search cost thousands of GPU hours.
A policy found on a proxy task is not optimal for larger models or datasets, because the best augmentation strength scales with model and data size.
How it works:
Start from a fixed list of about 14 ops: identity, rotate, shear x/y, translate x/y, autocontrast, equalize, solarize, posterize, color, contrast, brightness, sharpness.
For each image, sample
Nops uniformly at random (no learned probabilities).Apply each op at the global magnitude
M(e.g. on a 0–30 scale).
Why it works:
Diversity from random op combinations matters more than finely tuned per-op probabilities.
Tuning
(N, M)directly on the real task lets the regularization strength match the model. Larger models typically want a largerM.
Caveat: some ops can be label-unsafe for a task (e.g. heavy rotation for digits, color ops for color-defined classes). Prune the op list accordingly.
Q37.How do you transform ground-truth keypoint annotations during a horizontal flip augmentation?
Flipping the image means you must mirror each keypoint's x-coordinate and also swap the semantic identity of left/right keypoint pairs. If you only mirror x, the point labelled "left eye" ends up on the subject's right side, and the model learns contradictory labels.
Mirror the coordinates:
For continuous coordinates:
x' = W - x. For integer pixel indices:x' = W - 1 - x. Be consistent with your convention, because an off-by-one shifts every point.yis unchanged.
Swap left/right pairs:
Use a flip-index map, e.g.
left_eye↔right_eye,left_wrist↔right_wrist. Midline points (nose, neck) map to themselves.Visibility flags and per-keypoint confidences move with the swap.
Update related annotations:
Boxes:
x1' = W - x2,x2' = W - x1so thatx1 < x2still holds.For heatmap targets, either flip the heatmaps and reorder their channels with the same map, or regenerate them from the transformed points.
Same logic applies to flip test-time augmentation: flip the predicted heatmaps back and swap channels before averaging.
Q38.Why does Cutout help prevent a vision network from overfitting to specific visual cues?
Cutout randomly masks a contiguous square of the input image during training. Any single discriminative cue (a bird's beak, a logo, a background patch) is sometimes missing, so the network cannot depend on it alone. It has to spread its evidence across many parts of the object and its context.
Mechanism:
Zero (or mean-fill) a fixed-size square at a random location, usually with some probability. The square may extend past the image border.
The label stays the same, so the model must classify correctly from the remaining visible evidence.
Why it regularizes:
It acts like input-level dropout, but on spatially contiguous regions. Ordinary per-pixel or per-activation dropout is weak in conv nets because neighbouring pixels are highly correlated, so dropped information can be recovered from them.
Removing whole regions breaks co-adaptation on a single high-response feature. This pushes the network toward redundant, distributed representations.
It simulates occlusion, which improves robustness to partially hidden objects at test time.
Practical notes:
Patch size is the key hyperparameter: it should be relative to the object size, and patch size matters more than patch shape.
Risk: on small objects the mask can erase the whole object, which effectively creates label noise.
Successors: Random Erasing randomizes patch size and aspect ratio. CutMix fills the hole with another image and mixes the labels proportionally, so the masked pixels are not wasted.
Q39.When can a standard augmentation such as a horizontal flip silently corrupt your labels?
A flip corrupts labels whenever the label depends on orientation or handedness, i.e. the class or target is not invariant to mirroring. It is silent because training still converges: the model just learns contradictory or averaged targets, and accuracy drops without any error being raised.
Chirality-defined classes:
Text and characters:
b/d, mirrored digits, OCR in general.Directional signs: "turn left" vs "turn right" arrows. A flip turns one class into the other.
Gestures and actions: "swipe left", "point right" in images or video.
Targets with a left/right component:
Keypoints: x is mirrored but left/right joint identities are not swapped.
Regression targets: steering angle, yaw, gaze direction, or horizontal optical flow must be negated.
Segmentation classes such as "left lane" vs "right lane".
Domains with real anatomical or world asymmetry:
Medical imaging: heart position, laterality markers, and left vs right organs. A flip can fabricate a pathology (dextrocardia).
Driving scenes: which side of the road traffic drives on. Vertical flips similarly break scenes where gravity matters.
How to catch it:
Explicitly ask whether the label is invariant to the transform before adding it.
Visualize augmented samples with their labels overlaid.
Use label-aware transforms (swap or negate targets), or drop the augmentation entirely.
Q40.What makes fine-grained image classification distinct from standard object classification?
Fine-grained classification separates subcategories of the same basic class: bird species, car models, aircraft variants. The defining difficulty is that classes differ in small, localized details while images within one class vary a lot in pose, viewpoint, lighting, and background. Global, coarse features that work for "dog vs car" are not enough.
Low inter-class, high intra-class variance:
Two warbler species may differ only in wing-bar colour.
The same species looks very different perched vs flying, so the discriminative signal is a small fraction of the pixels.
Localized, part-based cues: The evidence lives in specific parts (beak, headlights, tail fin). Downsampling to 224px can destroy it, so higher input resolution often helps a lot.
Data and labelling challenges:
Labels need domain experts, so datasets are small, noisy, and often long-tailed (CUB-200-2011, Stanford Cars, FGVC-Aircraft, iNaturalist).
Augmentations can destroy the cue: colour jitter on colour-defined species, or crops that cut out the key part.
Typical methods:
Part localization or attention-guided crops that zoom into discriminative regions.
Second-order features such as bilinear pooling, which capture interactions between local features.
Metric learning losses that pull same-class embeddings together and push near-identical classes apart.
ViT patch or token selection, and strong pretrained backbones fine-tuned at high resolution.
Q41.How do you decide which pretrained backbone to select for a given classification task?
Pick the backbone by working backward from deployment constraints, then from how well its pretraining matches your data. Shortlist a few candidates on the accuracy/efficiency Pareto front and decide empirically with a cheap linear-probe or short fine-tune on your own validation set.
Deployment constraints first:
Constraints include latency budget, memory, target hardware (GPU, mobile, edge NPU), and batch size.
Check that the model supports quantization and export (ONNX, TensorRT, TFLite). Some ops such as certain attention variants may not be supported on the target.
Constraints alone often rule out large ViTs and favour MobileNet/EfficientNet-style models.
Data size and domain match:
With little data, prefer strong pretraining. CNNs' locality inductive bias also helps; ViTs need large data or large-scale pretraining.
With a big domain gap (medical, satellite, microscopy), consider self-supervised or domain-specific pretraining. Generic features such as DINOv2 often transfer better than supervised ImageNet-1k ones.
For tasks that benefit from semantics or zero-shot ability, consider CLIP-style backbones.
Task properties:
Required input resolution: small fine details need high resolution and backbones that remain efficient at that size.
Whether you need dense features for later detection or segmentation heads.
Validate empirically:
Shortlist 3–5 models (e.g. from
timm) at different size points.Run a linear probe on frozen features: fast, and a good proxy for transferability.
Fully fine-tune the top candidates and measure accuracy and latency on the real hardware.
Practical: also check license, weights availability, and team familiarity.
Q42.How does RoIAlign resolve the spatial misalignment present in RoIPool?
RoIPool quantizes twice (RoI coordinates to the feature grid, then bin boundaries to integers), misaligning extracted features from the true region; RoIAlign removes all rounding and uses bilinear interpolation to sample features at exact floating-point locations.
The problem with RoIPool:
An RoI at x = 100.6 px on a stride-16 map becomes 6.29, rounded to 6: an error of up to ~16 px in the image.
Bins are also rounded, so cells have unequal sizes and shifted positions.
Fine for classification, but harmful for pixel-accurate tasks like masks and small-object boxes.
How RoIAlign works:
Map the RoI to feature coordinates without rounding (e.g. keep 6.29).
Split it into equal output bins (e.g. 7×7) with fractional boundaries.
Place regular sample points in each bin (typically 2×2) and compute each value by bilinear interpolation from the 4 nearest feature cells.
Aggregate samples per bin by average (or max).
Impact:
Introduced in Mask R-CNN; markedly improved mask accuracy and also box AP, especially at strict IoU thresholds.
Fully differentiable with respect to features; available as
torchvision.ops.roi_align.
Q43.What problem does the Feature Pyramid Network solve across varying object scales?
FPN gives detectors features that are both semantically strong and high-resolution at every scale: it adds a top-down pathway with lateral connections to a CNN backbone, so small objects get detected on fine maps that still carry deep semantics, cheaply compared with image pyramids.
The problem:
Deep layers are semantically rich but coarse (stride 32): small objects vanish.
Shallow layers are high-resolution but semantically weak.
Image pyramids fix this but run the network per scale (slow); SSD-style use of raw backbone layers suffers from weak shallow features.
The architecture:
Bottom-up: normal backbone producing C2–C5.
Top-down: upsample the coarser map by 2×.
Lateral: a 1×1 conv on the matching backbone map, added element-wise.
A 3×3 conv smooths each merged map, giving P2–P5 with a shared channel count (256).
How it's used:
Objects are assigned to levels by size: small to P2, large to P5; a shared head runs on all levels.
Standard in Faster/Mask R-CNN, RetinaNet; variants include PANet (extra bottom-up path) and BiFPN.
Q44.How does a Region Proposal Network generate candidate bounding boxes?
An RPN slides a small conv network over the backbone feature map and, at each location, scores k anchor boxes for objectness and regresses offsets to refine them; the top-scoring refined boxes after NMS become proposals for the second stage.
Architecture:
A 3×3 conv on the shared feature map, followed by two sibling 1×1 convs.
Classification branch: objectness score per anchor (2k or k outputs).
Regression branch: 4k outputs
(tx, ty, tw, th)relative to each anchor.Anchors: typically 3 scales × 3 aspect ratios = 9 per location (or one scale per level with FPN).
Training:
Anchors with IoU > 0.7 to a ground truth (or the best match) are positive, < 0.3 negative, others ignored.
Sample ~256 anchors per image, up to 1:1 positive:negative; loss = binary cross-entropy + smooth L1 on positives.
Inference:
Apply predicted deltas to anchors and clip to the image.
Keep top-N by objectness, drop tiny boxes.
NMS (IoU ~0.7), keep ~300–2000 proposals for RoIAlign and the detection head.
Key benefit: proposals are learned and share backbone computation, replacing slow hand-crafted Selective Search.
Q45.What problem does Soft-NMS solve compared to standard greedy NMS?
Greedy NMS deletes every box whose IoU with a higher-scoring box exceeds a threshold. That wrongly kills true detections of heavily overlapping objects, which hurts recall in crowded scenes. Soft-NMS instead decays the scores of overlapping boxes in proportion to their overlap, so these detections survive with lower confidence.
The failure mode of greedy NMS:
It makes a hard binary decision: if IoU >
N_t(e.g. 0.5), the box's score is set to 0.Two real objects that overlap (people in a crowd, parked cars) collapse into one detection, so you lose recall.
It is very threshold-sensitive. A low
N_tmisses overlapping objects. A highN_tleaves duplicates, which costs precision.
Soft-NMS rescoring:
Linear:
s_i = s_i * (1 - IoU(M, b_i))when IoU ≥N_t.Gaussian:
s_i = s_i * exp(-IoU² / σ), which is continuous and has no hard threshold.Heavily overlapping duplicates fall below the final score threshold. Moderately overlapping true objects keep enough score to be counted.
Practical benefits:
It is a drop-in, inference-only change: no retraining, and the complexity matches greedy NMS (O(N²)).
The original paper (Bodla et al., 2017) reported consistent COCO mAP gains of roughly 1–2 points, mostly at higher IoU thresholds and in crowded scenes.
Limitations:
It is still a hand-crafted heuristic, and it does not remove false positives that don't overlap anything.
Related alternatives include DIoU-NMS, learned NMS, and NMS-free detectors such as DETR.
Q46.What is the difference between anchor-based and anchor-free object detectors?
Anchor-based detectors regress offsets relative to a dense set of predefined reference boxes (anchors). Anchor-free detectors predict boxes directly from points or keypoints on the feature map, with no box priors. Much of the practical gap between them comes from how each assigns positive and negative training samples.
Anchor-based (Faster R-CNN, SSD, RetinaNet, YOLOv2–v5):
Each feature-map location holds K anchors with different scales and aspect ratios.
Anchors are labeled positive or negative by IoU with ground truth (e.g. >0.5 or <0.4). The network predicts a class plus offsets
(dx, dy, dw, dh)for each anchor.Downsides: many hyperparameters (sizes, ratios, IoU thresholds) that must be tuned per dataset, a huge number of mostly-negative anchors (class imbalance), and poor fit to unusual shapes.
Anchor-free:
Point/center-based (FCOS, YOLOX, YOLOv8): each location predicts a class and its distances to the four box edges, or a center offset plus size.
Keypoint-based (CornerNet, CenterNet): predict heatmaps of corners or centers, then regress size or group the keypoints.
Benefits: fewer hyperparameters, fewer predictions (faster heads and post-processing), and better generalization to odd aspect ratios.
Challenges: ambiguous assignment when objects overlap. This is handled with FPN scale ranges, center sampling, or a center-ness or quality branch.
Key insight (ATSS paper):
When RetinaNet and FCOS used the same sample-assignment strategy, most of their accuracy gap disappeared.
Label assignment (fixed IoU vs. adaptive or dynamic, e.g. ATSS, SimOTA, TAL) matters more than anchors themselves.
Common ground: both styles are dense detectors that still typically need NMS.
Q47.How do anchor-free object detectors such as FCOS predict bounding boxes?
FCOS treats detection as per-pixel prediction. Every feature-map location that falls inside a ground-truth box regresses its four distances to that box's edges (l, t, r, b) and predicts a class. A center-ness branch then down-weights low-quality boxes predicted from locations far from the object center.
Per-location prediction:
A feature location on a level with stride s maps back to image point
(x, y).If that point lies inside a GT box (or, in later versions, inside a center region of it), the location is positive and its regression target is
l = x - x1, t = y - y1, r = x2 - x, b = y2 - y.Regression outputs pass through
expor ReLU (scaled per level) so the distances stay positive.
Multi-level assignment via FPN:
Each level P3–P7 handles a size range. A location is positive on a level only if max(l, t, r, b) falls within that level's range (0–64, 64–128, … , 512–∞).
This resolves most overlap ambiguity. Any remaining ambiguity goes to the GT box with the smallest area.
Center-ness branch:
Target:
sqrt( min(l,r)/max(l,r) * min(t,b)/max(t,b) ), which is 1 at the center and approaches 0 at the box edge.At inference it is multiplied into the class score, so off-center, poorly localized boxes rank low and get removed by NMS.
Losses: focal loss for classification, IoU/GIoU loss for the box, and BCE for center-ness.
Q48.How does DETR formulate object detection as a direct set prediction problem?
DETR outputs a fixed-size set of N predictions in one pass. During training it uses the Hungarian algorithm to find a one-to-one matching between predictions and ground-truth objects, then computes the loss only on matched pairs. Because each object can be claimed by only one prediction, the model learns not to emit duplicates, which removes the need for anchors and NMS.
Architecture:
A CNN backbone produces features, which a transformer encoder (global self-attention over pixels) processes.
A transformer decoder takes N learned object queries (e.g. 100) and produces N output embeddings in parallel.
Shared FFNs map each embedding to class probabilities (including a "no object" class ∅) and a normalized box
(cx, cy, w, h).
Bipartite matching:
Pad the ground truth with ∅ up to N entries.
Build a cost matrix: −p(class) + λ₁·L1(box) + λ₂·(−GIoU).
Solve for the minimum-cost permutation with the Hungarian algorithm (
scipy.optimize.linear_sum_assignment).
Set loss:
Cross-entropy on every prediction (unmatched ones are pushed toward ∅, with down-weighted loss), plus L1 and GIoU loss on matched boxes.
Auxiliary losses are applied after every decoder layer to help optimization.
Why this replaces NMS:
The loss is permutation-invariant and the matching is unique, so duplicates are penalized as ∅.
Decoder self-attention lets queries coordinate who predicts which object.
Q49.How did Fast R-CNN improve on the original R-CNN pipeline?
Fast R-CNN runs the CNN once per image instead of once per region proposal. It extracts each region's features from the shared feature map with RoI pooling and trains classification and box regression jointly in one network. This made it far faster (about 9× in training and ~200× at test with VGG16) and more accurate than R-CNN.
R-CNN's problems:
Each of ~2000 selective-search proposals is warped and passed through the CNN separately. This is massively redundant (tens of seconds per image).
Training is multi-stage: fine-tune the CNN, then train SVMs and box regressors separately on features cached to disk.
Shared computation + RoI pooling:
The whole image goes through the conv layers once. Proposals are projected onto the conv feature map.
RoI pooling max-pools each region into a fixed grid (e.g. 7×7), so FC layers can process regions of any size.
Single-stage, end-to-end training:
Two sibling heads, softmax over K+1 classes and per-class box regression, replace the SVMs and separate regressors.
A multi-task loss (cross-entropy + smooth L1) updates all layers. No features are cached to disk.
Hierarchical sampling (e.g. 2 images × 64 RoIs per minibatch) shares computation across RoIs from the same image.
Extras: truncated SVD on the FC layers speeds up detection.
Remaining bottleneck: selective search proposals stay external and slow. Faster R-CNN fixed this with a learned Region Proposal Network.
Q50.Why is Smooth L1 loss preferred over L2 loss for bounding box regression?
Smooth L1 behaves like L2 for small errors (smooth, shrinking gradients near the target) but like L1 for large errors (constant, bounded gradients). This keeps training stable when some box offsets are far off, while still converging precisely.
Problem with L2:
The gradient is proportional to the error, so badly matched boxes (common early in training or from poor anchors) produce huge gradients.
Outliers dominate the loss, which can destabilize training. Fast R-CNN needed careful learning-rate tuning to avoid exploding gradients with L2.
Problem with pure L1:
It is robust to outliers, but its gradient has constant magnitude and is non-differentiable at 0.
Updates don't shrink near the target, so the model can oscillate around the optimum.
Smooth L1 combines both (introduced in Fast R-CNN):
Quadratic region (|x| < β): the gradient decays toward zero, giving fine convergence.
Linear region (|x| ≥ β): the gradient is capped at magnitude 1, which bounds the influence of outliers.
β = 1 in the original paper. Many implementations use smaller values, such as 1/9 in Detectron.
Limitation: it is still a per-coordinate loss that does not directly optimize IoU. This motivated IoU, GIoU, DIoU and CIoU losses.
Q51.What problem does focal loss solve in one-stage detectors like RetinaNet?
Focal loss addresses extreme foreground-background class imbalance in dense one-stage detectors. RetinaNet evaluates around 100k anchors per image, and almost all of them are easy background. Under cross-entropy, those easy negatives collectively overwhelm the loss and gradient, even though each one contributes very little.
Why one-stage detectors suffer more:
Two-stage detectors filter candidates first: the RPN keeps about 2k proposals, and minibatches are sampled at a fixed ratio such as 1:3 positive:negative.
One-stage detectors classify every anchor directly, so the negative:positive ratio can reach about 1000:1.
The fix: down-weight easy examples:
FL(p_t) = -α_t (1 - p_t)^γ log(p_t)The modulating factor
(1 - p_t)^γapproaches 0 for well-classified examples (p_t close to 1). Training therefore focuses on hard, misclassified ones.γ = 2andα = 0.25worked best in the paper. With γ = 2, an example at p_t = 0.9 gets roughly 100x less loss than under cross-entropy.
Supporting tricks in RetinaNet:
The classifier bias is initialized so the foreground prior is π ≈ 0.01. This prevents a huge background loss in the first iterations.
The total loss is normalized by the number of positive anchors, not the total number of anchors.
Result: no need for hard-negative mining or sampling heuristics, and one-stage accuracy matched or beat two-stage detectors of the time.
Q52.What is the primary drawback of using L1 or L2 loss for bounding box regression compared to IoU-based losses?
L1 and L2 losses treat box coordinates as independent numbers, but detection is evaluated by IoU. Minimizing coordinate error is therefore not the same as maximizing overlap, and the losses are not scale-invariant.
Mismatch with the evaluation metric:
Several predictions with the same L1/L2 loss can have very different IoUs with the ground truth, depending on which coordinates are wrong.
The optimizer can lower the loss without improving mAP.
No scale invariance:
A 10-pixel error is minor on a large box but severe on a small one, yet the raw loss is identical.
Large boxes dominate the loss. Normalized offsets and log-space width/height targets only partially mitigate this.
Coordinates are coupled in reality: x, y, w and h jointly determine overlap, but separate per-coordinate terms ignore this interaction.
IoU-based losses fix this:
They optimize the metric directly, treat the box as one unit, and are scale-invariant.
Caveat: plain IoU loss has zero gradient when boxes don't overlap. GIoU, DIoU and CIoU were introduced to address this.
Q53.How does GIoU loss handle cases where two bounding boxes do not overlap at all?
GIoU adds a penalty based on the smallest box enclosing both boxes. When the boxes don't overlap, IoU is 0 and gives no gradient, but the penalty term still shrinks as the boxes move closer. That provides a useful training signal.
Definition:
GIoU = IoU - |C \ (A ∪ B)| / |C|, where C is the smallest axis-aligned box covering both A and B.GIoU ranges over [-1, 1], and the loss
1 - GIoUranges over [0, 2].
Non-overlapping behavior:
IoU = 0, so GIoU = -(empty space in C) / |C|.
Far-apart boxes leave C mostly empty, so GIoU approaches -1. Moving the prediction toward the target reduces the empty area, which gives a nonzero gradient.
Properties: It is scale-invariant and a lower bound on IoU. It equals IoU when the boxes coincide.
Limitations:
When one box contains the other, C equals the larger box, so the penalty is 0 and GIoU degenerates to IoU.
Convergence is slow: the prediction tends to grow first to create overlap, then shrink. DIoU and CIoU penalize center distance directly to avoid this.
Q54.What additional geometric properties does CIoU loss penalize compared to standard IoU loss?
CIoU extends IoU with two extra penalties. One is for the normalized distance between box centers; the other is for aspect-ratio mismatch. It therefore accounts for three geometric factors: overlap area, center distance and aspect ratio.
Formula:
L_CIoU = 1 - IoU + ρ²(b, b_gt) / c² + α·vCenter-distance term (from DIoU):
ρis the Euclidean distance between the box centers, andcis the diagonal of the smallest enclosing box.It pulls centers together directly, even when the boxes don't overlap or one contains the other, which is where GIoU stalls. It also converges faster.
Aspect-ratio term:
v = (4/π²)·(arctan(w_gt/h_gt) - arctan(w/h))²measures the difference in aspect ratio.α = v / ((1 - IoU) + v)is a trade-off weight. Shape matching gains priority once overlap is already high.
Usage: CIoU is the default box loss in several YOLO versions (v4/v5/v8). Its aspect-ratio term was later criticized (EIoU, SIoU) because it penalizes the w/h ratio rather than w and h individually.
Q55.What is the difference between mAP@0.5 and COCO mAP@[0.5:0.95]?
mAP@0.5 evaluates at a single, lenient IoU threshold, so it mostly measures whether objects are found. COCO mAP@[0.5:0.95] averages AP over 10 IoU thresholds (0.50, 0.55, …, 0.95), so it also rewards precise localization.
mAP@0.5 (PASCAL VOC style):
Any box with IoU ≥ 0.5 counts as a TP, so loose boxes earn full credit.
Good when coarse localization is enough, for example counting or presence detection.
COCO mAP (
APorAP@[.5:.95]):For each IoU threshold, compute AP for each class using 101-point interpolation.
Average over the 10 thresholds and over all classes.
A box at IoU 0.7 counts as a TP at only 5 of the 10 thresholds, so it gets partial credit.
Practical implications:
COCO mAP is always ≤ mAP@0.5 and is usually much lower (for example, 0.40 vs 0.60).
Improvements to box regression show up strongly in COCO mAP but barely move mAP@0.5.
COCO also reports
AP50,AP75, and size-splitAPs/APm/APlfor diagnosis.
Q56.How is Average Precision derived from the precision-recall curve in object detection?
AP is the area under a class's precision-recall curve. You build the curve by ranking detections by confidence and accumulating TPs and FPs. You then make precision monotonically non-increasing and integrate it over recall. mAP is the mean of AP across classes (and, in COCO, across IoU thresholds).
Build the PR curve:
Pool all detections of one class across the dataset and sort them by score, highest first.
Label each detection TP or FP via IoU matching against GT.
At each rank k: precision = cumTP/k, recall = cumTP/num_GT.
Interpolate (precision envelope):
p_interp(r) = max precision at any recall ≥ r.
This removes the zig-zag wiggles, because you could always choose a lower threshold that gives higher recall and precision at least that high.
Integrate:
All-point (VOC2010+): sum of Δrecall × p_interp at every recall change.
Sampled: 11 points (VOC2007) or 101 points (COCO), averaged.
Key property: AP is threshold-free. It summarizes ranking quality across all confidence cutoffs rather than at one operating point.
Q57.Why can duplicate detections of the same object never be counted as multiple true positives in mAP?
The evaluation uses one-to-one matching: each ground-truth object can be matched by at most one detection. Extra boxes on an already-matched object are counted as false positives. Otherwise a detector could inflate its score just by emitting many copies of each box.
Why the rule must exist:
Recall is TP / num_GT. Counting duplicates would let recall exceed 1, which is meaningless.
Precision would be inflated by box spam, so a detector without NMS could beat a clean one.
The metric should reflect what a user needs: one output per real object.
How it is enforced:
Detections are processed in descending confidence order. The first one that sufficiently overlaps a GT claims it, and later overlapping ones become FPs.
So the highest-scoring duplicate wins, which rewards correct ranking.
Consequence:
Duplicates actively lower AP. A high-confidence duplicate inserts a FP early in the ranking and drags precision down.
This is why NMS (or set-based matching, as in DETR's Hungarian loss) matters for mAP.
Q58.What is the difference between 11-point interpolated AP and all-point PR curve integration?
Both methods use the interpolated (monotonic) precision envelope; they differ in how they sample it. 11-point AP averages the envelope at recall = 0, 0.1, …, 1.0 (VOC2007). All-point AP computes the exact area under the envelope at every recall value where it changes (VOC2010+).
11-point interpolated AP:
AP = (1/11) Σ p_interp(r) for r ∈ {0, 0.1, …, 1}, where p_interp(r) = max precision at recall ≥ r.
This is coarse: changes between sample points are invisible, so it can over- or under-estimate the true area.
Low-AP methods are hard to tell apart, and a detector that never reaches recall 0.1 scores near 0.
All-point integration:
AP = Σ (r_{i+1} − r_i) · p_interp(r_{i+1}) over every recall step.
This is the exact area of the step function, so it is more sensitive and better at separating close methods.
Related: COCO uses 101-point sampling (0:0.01:1), which closely approximates all-point AP.
Practical note: numbers computed with different schemes are not directly comparable, so always state which protocol you used.
Q59.What does it indicate about localization when a detector's mAP@0.5 is high but mAP@0.75 is low?
It means the detector finds and classifies objects well, but its boxes are imprecise. Many detections overlap the GT well enough for IoU 0.5 but not for 0.75, so the bottleneck is box regression, not recognition.
Interpretation:
Detections with IoU between 0.5 and 0.75 count as TPs at 0.5 but as FP plus FN at 0.75.
Recognition and recall are fine; boxes are shifted, loose, or mis-sized.
COCO mAP@[.5:.95] will also be relatively low.
Common causes:
Coarse feature stride or low input resolution, especially for small objects.
Weak regression loss (plain L1/Smooth-L1 is not aligned with IoU) or a low regression loss weight.
Poor anchor priors, or a lenient positive-assignment IoU that trains on poorly aligned samples.
Noisy or inconsistent annotation boundaries (this caps the achievable high-IoU AP).
Remedies:
IoU-based losses: GIoU, DIoU, CIoU.
Iterative refinement: Cascade R-CNN with increasing IoU thresholds.
Higher resolution and FPN features.
Localization-aware scoring: IoU-aware or quality branches, so the best-aligned box survives NMS.
Q60.What is the purpose of Atrous Spatial Pyramid Pooling in DeepLab?
ASPP captures multi-scale context: it applies several atrous (dilated) convolutions with different dilation rates in parallel on the same feature map, so each pixel sees small, medium and large context windows without losing resolution, which helps segment objects of very different sizes.
Why atrous convolution:
Inserting gaps between kernel weights enlarges the receptive field with no extra parameters and no downsampling.
DeepLab keeps an output stride of 8 or 16 instead of 32, preserving spatial detail for dense prediction.
ASPP structure (DeepLabv3):
One 1×1 conv plus three 3×3 atrous convs (rates 6, 12, 18 at output stride 16).
An image-level branch: global average pooling, 1×1 conv, upsample back.
All branches are concatenated and fused with a 1×1 conv.
Why the image-pooling branch: At large rates most of a 3×3 kernel falls on padding, so it degenerates toward a 1×1 filter; global pooling supplies true whole-image context instead.
Idea origin: like spatial pyramid pooling, but resampling via dilation instead of pooling, so scales are captured in one forward pass rather than with an image pyramid.
Q61.Why is Dice loss often preferred over cross-entropy for medical image segmentation?
Medical targets (tumors, lesions) often occupy a tiny fraction of the image. Pixel-wise cross-entropy is dominated by the abundant background, while Dice loss measures overlap relative to the size of the foreground, so it is inherently robust to this imbalance and directly optimizes the metric used for evaluation.
The imbalance problem with cross-entropy:
CE averages per-pixel losses; with 99% background, predicting all background already gives low loss, and the model can under-segment the lesion.
Fixes exist (class weights, focal loss) but need tuning.
How Dice loss behaves:
Soft Dice:
1 - (2·Σ p·g + ε) / (Σ p + Σ g + ε)using predicted probabilities p and ground truth g.True negatives (background correctly predicted) do not appear, so the huge background cannot dominate.
It aligns training with the Dice score reported in medical benchmarks.
Caveats:
Gradients can be unstable for very small or empty targets;
εsmoothing is needed, and empty-mask images are poorly handled.Poorly calibrated probabilities compared with CE.
In practice: combine them (Dice + CE, as in nnU-Net) to get CE's stable gradients and Dice's imbalance robustness.
Q62.Why can pixel accuracy give misleadingly high scores in semantic segmentation?
Pixel accuracy counts the fraction of correctly labeled pixels, so it is dominated by large classes like background, road or sky. A model can ignore small or rare classes entirely and still score very high.
Class imbalance:
If background is 95% of pixels, predicting "background" everywhere yields 95% accuracy with zero useful output.
Small, often critical classes (pedestrians, lesions, poles) barely move the number.
No penalty structure for false positives per class: It treats every pixel equally, so boundary errors on a rare object are invisible against millions of easy pixels.
Better alternatives:
Mean IoU: per-class TP / (TP + FP + FN), averaged so each class counts equally.
Mean per-class accuracy (class-balanced recall), Dice/F1 per class, and boundary metrics for edge quality.
Q63.What is the difference between the Dice coefficient and IoU?
Both measure overlap between prediction A and ground truth B: IoU (Jaccard) = |A∩B| / |A∪B|, Dice = 2|A∩B| / (|A| + |B|). They are monotonically related, but Dice is always ≥ IoU and penalizes errors less harshly.
Exact relationship:
Dice = 2·IoU / (1 + IoU); IoU = Dice / (2 − Dice).
Example: IoU 0.5 corresponds to Dice ≈ 0.67.
In confusion-matrix terms:
IoU = TP / (TP + FP + FN); Dice = 2TP / (2TP + FP + FN), which equals the F1 score.
Dice double-weights TP, so FP and FN cost relatively less.
Practical consequences:
For a single sample they rank predictions identically; averaged over a dataset or classes, rankings can differ because of the nonlinear mapping.
IoU is the convention in detection and natural-image segmentation (mIoU, AP thresholds); Dice dominates medical imaging and is used as a differentiable soft loss.
Q64.How does Mask R-CNN extend Faster R-CNN to generate instance masks?
Mask R-CNN adds a third, parallel head to Faster R-CNN: a small fully convolutional network that predicts a binary mask for each RoI, alongside the existing class and box heads. It also replaces RoIPool with RoIAlign so the pixel-level masks stay spatially aligned.
Mask branch:
A few conv layers plus a deconv on each RoI's features, outputting K masks of size m×m (typically 28×28), one per class.
Being fully convolutional, it preserves spatial layout instead of flattening into FC vectors.
RoIAlign:
RoIPool quantizes box coordinates and bins to integers, causing misalignment harmless for boxes but damaging for masks.
RoIAlign uses bilinear interpolation at exact float sample points, giving large gains in mask accuracy.
Decoupled mask and class prediction:
Per-pixel sigmoid with binary cross-entropy, applied only to the mask of the ground-truth class: classes do not compete (unlike a per-pixel softmax).
Total loss:
L = L_cls + L_box + L_mask.
Inference:
Run detection, keep top boxes after NMS.
Run the mask head on those boxes, take the mask for the predicted class.
Resize the m×m mask to the box size and threshold at 0.5.
Q65.How does the Segment Anything Model achieve promptable zero-shot segmentation?
SAM frames segmentation as a promptable task: given an image and any prompt (points, box, rough mask), return a valid mask. A heavy image encoder runs once, a light prompt-conditioned decoder runs in real time, and training on a massive, auto-generated dataset (SA-1B) lets it generalize to unseen objects and domains without fine-tuning.
Architecture:
Image encoder: MAE-pretrained ViT (e.g. ViT-H) producing an image embedding, computed once per image.
Prompt encoder: points and boxes as positional encodings plus learned type embeddings; dense mask prompts via convs (free-text was explored only as a proof of concept).
Mask decoder: lightweight two-way transformer (prompt tokens attend to image, image attends to tokens), running in tens of milliseconds, enabling interactive use.
Handling ambiguity:
A single point may mean part, object or whole group, so SAM outputs 3 masks plus a predicted IoU score for each.
Training backpropagates only the lowest-loss mask, so outputs specialize to different granularities.
Training for promptability:
Simulates interactive sessions: sample prompts from ground truth, then add corrective points from error regions over several rounds.
Loss: focal + Dice on masks, MSE on IoU prediction.
Data engine (the main reason for zero-shot strength):
Assisted-manual: annotators correct SAM's masks.
Semi-automatic: SAM fills confident masks, humans add missed objects.
Fully automatic: grid of point prompts yields about 1.1B masks on 11M images.
Limitations: masks are class-agnostic (no semantic labels), fine structures and boundaries can be imperfect, and the encoder is expensive.
Q66.How does a Fully Convolutional Network produce spatially dense pixel predictions?
An FCN replaces every fully connected layer with convolutions, so the network outputs a coarse spatial grid of class scores instead of one vector. It then upsamples that grid back to input resolution with learnable transposed convolutions, fusing in finer features through skip connections, and trains with a per-pixel loss.
Convolutionalize the classifier:
FC layers are rewritten as convolutions (e.g. the first FC becomes a 7x7 conv, later ones become
1x1convs). Each output location is then a class-score vector for its receptive field.With no fixed-size FC layer, the network accepts any input size and produces a proportionally sized score map in a single forward pass. This is far cheaper than classifying sliding patches one at a time.
Upsample the coarse map: Pooling leaves the map at 1/32 of the input resolution. Transposed convolutions (
ConvTranspose2d), initialized as bilinear interpolation and then learned, bring it back to full H x W.Skip connections recover detail:
FCN-32s: upsamples the final layer directly, which gives blobby boundaries.
FCN-16s and FCN-8s: add score predictions from the
pool4andpool3layers. This combines deep "what" semantics with shallow "where" localization.
Dense training: The output is a C x H x W logit tensor, trained with softmax cross-entropy summed over all pixels. Ignored labels, such as void regions, are masked out of the loss.
Legacy: this encoder-decoder-with-skips pattern underlies U-Net, SegNet and DeepLab. DeepLab swaps some of the downsampling for dilated convolutions.
Q67.How does the Swin Transformer achieve linear computational complexity with respect to image size?
Swin computes self-attention only inside fixed-size local windows (M x M patches) instead of across all patches. Each window costs a constant amount, and the number of windows grows linearly with image area, so total cost is linear in image size. Shifting the windows between layers restores communication across windows.
The complexity math (h x w patches, C channels):
Global MSA: 4hwC² + 2(hw)²C. This is quadratic in the number of patches.
Window MSA: 4hwC² + 2M²hwC. With M fixed (typically 7), this is linear in hw.
Shifted windows:
Consecutive blocks alternate between regular windows and windows shifted by (M/2, M/2). Information therefore crosses window borders, and the receptive field grows with depth.
Shifting is implemented as a cyclic shift (
torch.roll) plus an attention mask. This keeps the window count constant, so there is no padding overhead.
Hierarchical design:
Patch merging concatenates each 2x2 group of neighboring patches and projects it, halving resolution and doubling channels.
This yields multi-scale feature maps at strides 4, 8, 16 and 32, like a CNN. These plug directly into FPN-style detection and segmentation heads.
Position encoding: Swin uses a relative position bias inside each window rather than absolute embeddings.
Trade-off: attention is no longer global in a single layer. Long-range context builds up gradually through shifting and downsampling.
Q68.Why is a learnable class token used in Vision Transformers rather than global average pooling over patch tokens?
The [CLS] token is largely a convention inherited from BERT. It gives the model a dedicated, learnable slot that aggregates global information through attention. It is not inherently better than GAP: the ViT authors showed GAP matches it once the learning rate is tuned, and many later models use GAP.
Why
[CLS]was used:It keeps the architecture identical to the NLP Transformer.
It acts as learned, content-dependent attention pooling: it can weight informative patches heavily rather than averaging uniformly.
Patch tokens stay free to encode local information, because they are not forced to also be good global summaries.
Why GAP is often preferred now:
No extra parameter or token, and it is more CNN-like and stable.
It pushes every patch token to carry semantic content, which helps dense downstream tasks.
Swin and many MAE fine-tuning recipes use GAP. Some models, such as DINOv2 heads, concatenate
[CLS]with the averaged patch tokens.
Practical notes: In self-supervised models like DINO,
[CLS]attention maps show emergent object segmentation, which makes them useful for interpretability.Interview takeaway: the choice is an empirical design decision, not a fundamental requirement.
Q69.How do you adapt a pretrained Vision Transformer to a higher input resolution than it was pretrained on?
Keep the patch size fixed, so a higher resolution simply produces more patch tokens. Then 2D-interpolate the learned positional embeddings to the new grid size and fine-tune briefly at the new resolution. The transformer weights themselves are resolution-agnostic.
Why the positional embeddings are the issue: Attention and MLP weights work on any sequence length. Learned absolute position embeddings, however, exist only for the pretraining grid (e.g. 14x14).
Interpolation procedure:
Split off the
[CLS]embedding.Reshape the patch embeddings to (D, 14, 14).
Resize them bicubically to the new grid (e.g. 24x24 for 384px).
Flatten and re-concatenate with the
[CLS]embedding.
Fine-tune at the target resolution: A short fine-tune lets the model adapt to the interpolated embeddings and changed object scales. Training low and testing high typically improves accuracy (the FixRes effect).
Watch the cost:
Token count grows with resolution squared, and attention cost grows with token count squared. Going from 224 to 384 means about 2.9x more tokens and about 8.6x more attention FLOPs.
Mitigations include windowed attention (as in ViTDet), FlashAttention, and token pruning or merging.
Alternatives:
Relative position schemes (Swin bias tables, RoPE) transfer more gracefully across resolutions.
FlexiViT resizes the patch size instead, keeping the token count constant.
Q70.How does Masked Autoencoder pretraining work for vision transformers?
MAE randomly masks a large fraction (about 75%) of image patches. A ViT encoder processes only the visible patches, and a small decoder reconstructs the pixels of the masked patches from them. Predicting missing content forces the encoder to learn semantic, holistic representations without any labels.
Pipeline:
Patchify the image and randomly drop 75% of patches, sampled uniformly.
The encoder (a standard ViT) sees only the roughly 25% visible patches plus their position embeddings. No mask tokens are used here.
The decoder receives the encoded visible tokens plus a shared learnable mask token at each masked position, all with position embeddings. It is a lightweight, narrow and shallow Transformer.
A linear head predicts the pixel values of each patch. The loss is MSE computed only on masked patches.
Key design choices:
High mask ratio: images are spatially redundant, so low masking can be solved by interpolating neighbors. At 75% the task requires real understanding.
Asymmetric encoder-decoder: the encoder runs on a quarter of the tokens, which gives about 3x or more pretraining speedup and makes large ViTs practical.
Per-patch normalized pixel targets improve representation quality.
After pretraining:
Discard the decoder and fine-tune the encoder on full, unmasked images for the downstream task.
MAE features shine under fine-tuning but are weaker under linear probing than contrastive methods like DINO.
Why it matters: it gives ViTs a data-efficient pretraining signal, addressing their data hunger without labels. It is the vision analogue of BERT's masked language modeling.
Q71.How does contrastive visual pretraining work in SimCLR?
SimCLR learns representations by making two random augmentations of the same image map to nearby embeddings while pushing apart embeddings of all other images in the batch, using a softmax-based contrastive loss (NT-Xent).
Pipeline:
Sample a batch of N images; apply two random augmentations to each, giving 2N views.
Encoder (e.g. ResNet-50) produces representation
h.A small MLP projection head maps
htoz, which is L2-normalized.Loss is computed on cosine similarities between all pairs of
z.
NT-Xent loss:
For each view, its partner view is the positive; the other 2N−2 views are negatives.
It is cross-entropy over similarities divided by a temperature τ: low τ sharpens focus on hard negatives.
Augmentations define the task:
Random crop plus color distortion is the critical combination; without color jitter the model can cheat by matching color histograms.
The network learns features invariant to these transformations (object identity, shape).
Key findings:
Projection head matters: use
h(before the head) for downstream tasks, sincezdiscards augmentation-related information.Needs large batches (4096+) for enough negatives, plus long training; this cost motivated MoCo's queue and negative-free methods.
Evaluation: linear probe on frozen features, or fine-tuning with few labels.
Q72.How does masked autoencoder pretraining differ conceptually from contrastive learning?
Contrastive learning is discriminative: it learns embeddings invariant to augmentations by telling instances apart. Masked autoencoders (MAE) are generative: they hide most image patches and learn by reconstructing the missing pixels, so the pretext task is prediction of content rather than comparison between samples.
Learning signal:
Contrastive: pull positives together, push negatives apart in embedding space.
MAE: regression loss (MSE) on the pixels of masked patches; no pairs, no negatives.
Inductive bias comes from different places:
Contrastive: hand-designed augmentations decide what to be invariant to (color, crop).
MAE: needs little augmentation; masking itself is the corruption, and the model must learn structure and context to fill gaps.
Architecture:
MAE uses an asymmetric ViT: encoder sees only visible patches (~25%), a light decoder reconstructs. This makes pretraining cheap.
Contrastive methods typically use two encoder passes (often siamese or momentum) plus a projection head.
Resulting features:
Contrastive features are more semantic and linearly separable: strong linear probe and retrieval out of the box.
MAE features keep more local/spatial detail: weaker linear probe, but excellent after fine-tuning, especially for detection and segmentation, and scale well with model size.
Failure modes: contrastive must avoid collapse and needs many negatives or tricks; MAE cannot collapse but may spend capacity on low-level texture.
Q73.How does CLIP train visual and textual representations in a shared embedding space?
CLIP trains an image encoder and a text encoder jointly on ~400M image-caption pairs with a symmetric contrastive loss: matched image-text pairs are pulled together and mismatched pairs in the batch pushed apart, so both modalities land in one shared, comparable embedding space.
Two encoders:
Image: ResNet or ViT; text: Transformer (uses the
[EOS]token output).Each followed by a linear projection to the same dimension, then L2-normalized.
Contrastive objective:
For a batch of N pairs, compute the N×N cosine similarity matrix scaled by a learned temperature.
Diagonal entries are positives; cross-entropy is applied over rows (image→text) and columns (text→image) and averaged.
Huge batches (32,768) give many negatives.
Why contrastive rather than captioning: Predicting exact caption words is harder and was ~4x less compute-efficient; matching which text goes with which image is easier and scales better.
Result: natural language acts as flexible supervision, enabling zero-shot classification and retrieval; limitations include weak counting/spatial reasoning and web-data biases.
Q74.How does CLIP perform zero-shot image classification using text prompts?
CLIP turns class names into text prompts, embeds them with the text encoder, and picks the class whose text embedding is most similar to the image embedding. The text embeddings effectively become the weights of a linear classifier, built without any training images.
Procedure:
Wrap each class in a template, e.g. "a photo of a {class}."
Encode all prompts and normalize: a matrix of class embeddings.
Encode the image and normalize.
Cosine similarity × temperature, softmax over classes, take argmax.
Why prompts matter:
Training captions are sentences, so a bare word like "crane" is ambiguous and off-distribution.
Context-specific templates ("a photo of a {}, a type of pet.") help on fine-grained datasets.
Prompt ensembling: average embeddings of many templates per class; gave a few points of ImageNet accuracy.
Strengths and limits:
Any label set at inference time; strong robustness to distribution shift.
Weak on abstract or specialized tasks (counting, medical, satellite) and sensitive to prompt wording; CoOp-style learned prompts or linear probes help.
Q75.How does the tracking-by-detection paradigm work in multi-object tracking?
Tracking-by-detection splits tracking into two steps: run an object detector independently on each frame, then link those detections across frames into identity-consistent tracks. Linking is a data association problem.
Detect:
A detector (YOLO, Faster R-CNN) outputs boxes and scores per frame.
Tracking quality is bounded by detection quality.
Predict: A motion model, usually a Kalman filter with constant velocity, predicts where each existing track should be in the current frame.
Associate:
Build a cost matrix between predicted tracks and detections.
Cost options: IoU, Mahalanobis distance, appearance embedding distance.
Solve the matching with the Hungarian algorithm, then reject matches above a cost threshold.
Update: Matched tracks correct their state with the detection.
Manage the track lifecycle:
Unmatched detections spawn tentative tracks, confirmed after N hits.
Unmatched tracks coast on predictions and are deleted after
max_agemissed frames.
Representative trackers:
SORT: Kalman filter plus IoU plus Hungarian.
DeepSORT: adds re-ID appearance features.
ByteTrack: also associates low-confidence detections in a second pass.
Trade-offs:
Pros: modular, fast, and benefits directly from better detectors.
Cons: missed detections and occlusions cause fragmentation and ID switches.
Contrast with joint detection-and-tracking (FairMOT, CenterTrack) and query-based trackers (MOTR).
Q76.What fundamental assumptions does the Lucas-Kanade optical flow method rely on?
Lucas-Kanade rests on three assumptions: brightness constancy, small motion, and spatial coherence (all pixels in a small window share the same flow). Together they turn the underdetermined per-pixel flow equation into a solvable least-squares problem.
Brightness constancy:
A point keeps its intensity as it moves: I(x+u, y+v, t+1) = I(x, y, t).
Violated by lighting changes, specularities, and shadows.
Small motion:
Displacement is small enough for a first-order Taylor expansion, giving Ixu + Iyv + It = 0.
Large motion is handled with image pyramids (coarse-to-fine) plus iterative refinement.
Spatial coherence:
Every pixel in a window (e.g. 5×5) shares the same (u, v), giving 25 equations for 2 unknowns.
Solve via the normal equations AᵀA·d = −Aᵀb.
Breaks at motion boundaries and for non-rigid motion inside the window.
Implied requirement: enough texture:
AᵀA (the structure tensor) must be well-conditioned, meaning both eigenvalues are large.
This holds at corners. Edges and flat regions are ill-conditioned: the aperture problem.
That is why LK is run on Shi-Tomasi corners (
cv2.goodFeaturesToTrack).
Q77.What is the role of the Kalman filter in SORT-style multi-object tracking?
In SORT, the Kalman filter is the motion model. It predicts where each track's box will be in the next frame so detections can be associated by IoU, and it fuses noisy detections into a smoothed state estimate over time.
State:
[u, v, s, r, u̇, v̇, ṡ]: box center, scale (area), and aspect ratio, plus their velocities.
Aspect ratio is assumed constant.
Uses a linear constant-velocity model.
Predict step:
Propagates each track forward one frame and grows its uncertainty (covariance).
The predicted boxes are what get compared with new detections in the IoU cost matrix for Hungarian matching.
Update step:
A matched detection corrects the state, weighted by the Kalman gain (relative trust in model vs measurement).
This smooths jittery boxes and estimates velocity, which is never directly observed.
Short-term occlusion handling: Unmatched tracks keep predicting (coasting) for a few frames, so a briefly missed object can be re-matched.
In DeepSORT: The filter's covariance also provides Mahalanobis-distance gating, which rules out physically implausible matches.
Limitation:
Constant velocity fails for erratic motion or long occlusions, where predictions drift.
This is why appearance cues and later trackers such as OC-SORT add corrections.
Q78.How does DeepSORT use appearance embeddings to reduce identity switches after occlusion?
DeepSORT adds a re-identification CNN embedding to each detection and keeps a memory of recent embeddings per track. When an object reappears after occlusion and its motion prediction has drifted, it can still be matched to its old track by visual similarity instead of being given a new ID.
Appearance descriptor: A small CNN trained on a person re-ID dataset maps each box crop to an L2-normalized 128-d vector.
Per-track gallery:
Each track stores up to about 100 recent embeddings.
Appearance cost = minimum cosine distance between the detection and any embedding in the gallery.
This is robust to pose and viewpoint changes over time.
Combined with motion:
Mahalanobis distance from the Kalman filter gates out implausible locations.
Cosine appearance distance mostly drives the actual matching.
Motion becomes unreliable during occlusion because uncertainty grows, so appearance carries re-identification.
Matching cascade:
Tracks are matched in order of time since last update, most recently seen first.
Long-lost tracks with diffuse covariance therefore don't steal detections from fresh ones.
Longer track survival: A larger
max_age(e.g. 30 frames) keeps occluded tracks alive long enough to be recovered by appearance.Limitations:
Similar-looking objects (uniformed players) still cause switches.
The re-ID net adds compute per detection and is domain-specific (trained on pedestrians).
Q79.How does the Hungarian algorithm resolve data association between predicted tracks and new detections?
The Hungarian algorithm takes a cost matrix between predicted tracks and new detections and finds the one-to-one assignment with minimum total cost in polynomial time (O(n³)). Thresholding then decides which assignments are real matches.
Build the cost matrix:
Rows are tracks and columns are detections.
Cost options: 1 − IoU (SORT), cosine plus Mahalanobis (DeepSORT), or a weighted combination.
Solve the global assignment:
Unlike greedy matching, it optimizes all pairs jointly, so one locally good match can't block a better global solution.
Rectangular matrices are padded with dummy rows or columns.
How it works (intuition):
Subtract each row's minimum, then each column's minimum.
Cover all zeros with the minimum number of lines.
If there are n lines, an optimal assignment exists among the zeros.
Otherwise, subtract the smallest uncovered value from uncovered entries, add it at line intersections, and repeat.
Post-process:
Reject assigned pairs whose cost exceeds a gate (e.g. IoU < 0.3).
Unmatched detections become new tracks.
Unmatched tracks age and are deleted after
max_age.
Q80.What is the difference between the MOTA and IDF1 metrics for multi-object tracking?
MOTA is a frame-level error count dominated by detection quality (misses and false positives). IDF1 is a trajectory-level score that measures how consistently each ground-truth object keeps the same predicted identity over time.
MOTA (Multiple Object Tracking Accuracy):
MOTA = 1 − (FN + FP + IDSW) / GT, summed over all frames after per-frame matching (usually IoU-based).FN and FP typically outnumber ID switches by orders of magnitude, so MOTA mostly reflects the detector.
An ID switch is counted once per event, regardless of how long the wrong identity persists.
It is unbounded below and can go negative when errors exceed the number of GT objects.
IDF1 (ID F1 score):
Runs a global one-to-one (bipartite) matching between whole predicted tracks and GT tracks, then counts identity-correct detections.
IDF1 = 2·IDTP / (2·IDTP + IDFP + IDFN).A track that takes on the wrong identity loses credit for every frame it stays wrong, so long-term identity preservation dominates.
Why they disagree:
A strong detector paired with a weak association step can score high MOTA and low IDF1.
Conservative tracking that misses some detections but never swaps identities can show the opposite pattern.
In practice: report both, plus HOTA, which explicitly balances detection accuracy (DetA) and association accuracy (AssA).
Q81.Why do keypoint estimation networks predict heatmaps rather than regressing direct (x, y) coordinates?
Heatmaps keep the output spatially aligned with the input, so a fully convolutional network can exploit translation equivariance and get dense, easy-to-optimize supervision. Direct regression forces the network to compress spatial evidence into two numbers through a highly nonlinear mapping.
Why heatmaps work better:
Translation equivariance: a keypoint that moves in the image moves in the heatmap the same way. Regression via fully connected layers throws away this structure.
Dense supervision: every pixel receives a target (a Gaussian centered on the joint), which gives richer gradients than a single L2 loss on (x, y).
Uncertainty and multimodality: the heatmap can express ambiguity (e.g. left vs. right wrist) or several instances. A regressor tends to average them into a wrong midpoint.
Empirically, heatmap models (Hourglass, SimpleBaseline, HRNet) historically beat regression by a wide margin.
Costs of heatmaps:
Quantization error: output stride (e.g. 4) limits precision. Mitigations include sub-pixel offsets, DARK decoding, or soft-argmax / integral regression.
High-resolution outputs cost memory and compute, and argmax post-processing is required.
Performance degrades on small inputs, where the heatmap becomes too coarse.
Modern alternatives narrow the gap:
Integral regression (differentiable soft-argmax over the heatmap) and SimCC (per-axis classification).
RLE (residual log-likelihood estimation) regression and transformer query-based regressors.
Q82.Why is CTC loss commonly used in text recognition pipelines?
CTC (Connectionist Temporal Classification) lets a recognizer train on word or line images with only the transcription string, without character-level positions. It does this by summing over every alignment between per-frame predictions and the target text.
The alignment problem:
A CRNN-style model (CNN, then BiLSTM or transformer) outputs a probability distribution per horizontal frame. There are T frames, usually many more than the number of characters.
Labeling which frame corresponds to which character is expensive and ill-defined, and CTC removes that need.
How it works:
Add a
blanktoken to the vocabulary.Define a collapse function: merge repeated symbols, then remove blanks (e.g. "hh-e-ll-ll-o" becomes "hello"). A blank is needed between genuine double letters.
The loss is −log Σ P(alignment) over all alignments that collapse to the target, computed efficiently with forward-backward dynamic programming.
Practical benefits:
Variable-length outputs come from a fixed-length frame sequence.
Decoding is fast and parallel (greedy best-path, or beam search with a language model), which makes it well suited to production and edge use.
Training is simple and stable, with built-in support such as
torch.nn.CTCLoss.
Limitations:
Frames are treated as conditionally independent, so there is no implicit language model.
It assumes monotonic 1D alignment and requires the target length to be ≤ T, which makes curved or 2D text harder.
For irregular text, attention or transformer decoders (e.g. ASTER, TrOCR, PARSeq) often perform better, at the cost of slower autoregressive decoding.