Back to interview questions

100+ Computer Vision Interview Questions and Answers

100+ Computer Vision Interview Questions and Answers

Explore 120 computer vision interview questions and answers on image processing, geometry, datasets, neural networks, detection, metrics, and inference.

Explore 120 computer vision interview questions and answers on image processing, geometry, datasets, neural networks, detection, metrics, and inference.

By

Team Sherlock.sh

Add Sherlock as a preferred source on Google

Computer vision turns images and video into measurements, predictions, and representations that support a defined task. A computer vision engineer must connect pixel-level choices and model behavior to the data, evaluation protocol, and deployment conditions that determine whether a system is useful.

This guide to 100+ Computer Vision Interview Questions and Answers contains 120 questions across beginner, intermediate, and experienced levels. It covers image processing, camera geometry, datasets, neural networks, detection, segmentation, evaluation metrics, training, and inference, with practical reasoning and focused numerical or coding examples.

How can recruiters detect AI-assisted cheating, deepfakes, and impersonation during Computer Vision interviews?

Computer vision interviews often combine a small image-processing or tensor exercise with questions about dataset splits, model errors, and evaluation. A candidate may need to explain a channel-order mismatch, calculate an overlap metric, or identify why a good validation score fails to reflect deployment conditions. Unauthorized real-time help can hide whether the candidate can connect the calculation or code to those assumptions.

Sherlock AI helps recruiters detect potential AI-assisted cheating, deepfakes, candidate impersonation, and unauthorized real-time assistance during computer vision engineering interviews.

Pair interview-integrity checks with a bounded example and follow-up changes to the input shape, class distribution, or deployment requirement. Ask candidates to explain intermediate results, identify failure cases, and choose a test that would challenge their explanation. Review suspicious activity in context rather than treating a signal as proof of misconduct.

Computer Vision Interview Questions

Choose questions that match the role's balance of image processing, geometry, model development, data work, and deployment. Start with representations and basic operations, then add evaluation, training, and system constraints. Agree on the task, input conventions, framework versions, and metric protocol before comparing approaches.

Computer Vision Interview Questions for Beginners

These beginner questions cover image representation, color, filtering, edges, transformations, geometry, basic learning concepts, and common vision tasks. They establish whether a candidate can reason about pixels, coordinates, labels, and simple evaluation results before selecting a complex model.

  1. What distinguishes computer vision from image processing, and how can they work together?

  2. How do image height, width, channels, and data type describe a digital image?

  3. How much uncompressed pixel storage does a 640-by-480 three-channel uint8 image require?

  4. Why can an image loaded with OpenCV have swapped red and blue colors in an RGB display?

  5. When might grayscale or HSV be more useful than RGB, and what information can be lost?

  6. How does scaling pixel values to a range differ from standardizing them with a mean and standard deviation?

  7. What trade-offs arise when resizing an image without preserving its aspect ratio?

  8. Why should categorical segmentation masks usually be resized differently from photographs?

  9. How do mean, Gaussian, and median filtering differ when reducing image noise?

  10. What does an image edge represent, and why can an edge detector respond strongly to noise?

  11. How do global, adaptive, and Otsu thresholding choose a foreground mask?

  12. What do erosion, dilation, opening, and closing do to a binary foreground region?

  13. What can an intensity histogram reveal, and what can histogram equalization change?

  14. What does a learned convolutional filter compute in a CNN?

  15. How do kernel size, stride, and padding change a convolution layer's output shape?

  16. Why might a CNN use pooling or a strided convolution to reduce spatial resolution?

  17. Why are nonlinear activation functions needed between learned linear layers?

  18. What does overfitting look like in training and validation results for an image classifier?

  19. How can data augmentation help a vision model, and when can an augmentation invalidate a label?

  20. Why should related images be kept together when creating train, validation, and test splits?

  21. How do image-level classes, bounding boxes, and pixel masks differ as training labels?

  22. Why do convolutional layers generally use fewer parameters than fully connected layers applied to all image pixels?

  23. How does using a pretrained model as a feature extractor differ from fine-tuning it?

  24. How do single-label and multilabel image classification differ?

  25. What extra predictions must an object detector make beyond an image classifier?

  26. How do semantic, instance, and panoptic segmentation describe a scene differently?

  27. What must be specified before interpreting four numbers as a bounding box?

  28. What is intersection over union, and what is its value when two boxes each have area 100 and overlap by 50?

  29. What do true positives, false positives, false negatives, and true negatives mean for a binary image classifier?

  30. How do precision and recall emphasize different kinds of classification error?

  31. Why can a classifier with high accuracy still be poor at finding a rare visual defect?

  32. What separate roles do the training, validation, and test datasets play?

  33. Why is the training loss not necessarily the metric used to select a useful vision model?

  34. How does running a trained model for inference differ from training it?

  35. What is the difference between detecting an image keypoint and describing it?

  36. How do translation, rotation, scaling, and perspective changes transform an image?

  37. What do camera intrinsics and extrinsics describe in the pinhole camera model?

  38. What does optical flow estimate, and how is it different from identifying an object?

  39. What privacy questions should be asked before collecting images for a vision dataset?

  40. Why must a deployed vision model be evaluated for latency and memory as well as predictive quality?

Computer Vision Interview Questions for Intermediate

These intermediate questions examine feature extraction, convolutional models, detection, segmentation, augmentation, losses, training behavior, and evaluation. They focus on implementing a pipeline whose data transformations, targets, and measurements remain consistent with the intended task.

  1. How would you write an OpenCV image-loading step that checks failure, channel order, shape, and value range before inference?

  2. Why can arithmetic on uint8 images wrap or saturate, and how would you safely compute an image difference?

  3. A pretrained classifier works in a notebook but fails in an API: how would you check for preprocessing mismatch?

  4. How would you apply the same random geometric augmentation to an image, its boxes, and its segmentation mask?

  5. How can border handling and output data type change the result of an image filter?

  6. How does cross-correlation differ from mathematical convolution, and which convention do common CNN layers use?

  7. How would you match local image descriptors and reject unreliable matches before estimating geometry?

  8. When is a homography a suitable model for aligning two images, and what can make its estimate unreliable?

  9. How would you calibrate a fixed camera and check whether its distortion correction is useful?

  10. For rectified stereo with focal length 800 pixels, baseline 0.12 meters, and disparity 24 pixels, what depth is estimated and what assumptions matter?

  11. What is the theoretical receptive field after three 3-by-3 convolutions with stride 1 and dilation 1, and how does a stride change the calculation?

  12. How many trainable parameters are in a 3-by-3 convolution from 16 to 32 channels with groups equal to 1 and one bias per output channel?

  13. How does a residual connection help optimize a deep network, and what happens when tensor shapes differ?

  14. How would you freeze and then fine-tune a pretrained backbone without unintentionally changing its preprocessing or normalization behavior?

  15. What logits and target shapes does PyTorch cross-entropy expect for multiclass classification and semantic segmentation?

  16. When would you use binary cross-entropy with logits instead of multiclass cross-entropy for image predictions?

  17. Why are model.eval() and disabling gradient recording separate steps in PyTorch inference?

  18. How would you tell whether slow training is caused by image decoding, augmentation, data transfer, or model computation?

  19. How would you split a dataset containing adjacent video frames and repeated views of the same physical item?

  20. How would you compare class weighting, resampling, and collecting more labels for an imbalanced vision task?

  21. How would you select hyperparameters and an early-stopping point without repeatedly tuning against the test set?

  22. How do one-stage and two-stage detectors organize their predictions, and why is neither always faster or more accurate?

  23. How would you implement or explain greedy non-maximum suppression for scored boxes of one class?

  24. How does detection average precision summarize a ranked set of predictions, and how does COCO-style AP differ from AP at IoU 0.50?

  25. Why can two high-overlap predictions for one ordinary ground-truth object count as one true positive and one false positive?

  26. Why do object detectors combine classification and localization losses, and how does focal loss change the emphasis on easy examples?

  27. How can a feature pyramid help detect small and large objects in the same image?

  28. How do an encoder-decoder structure and skip connections support semantic segmentation?

  29. How are Dice and IoU related for the same nonempty binary masks, and what policy is needed for empty masks?

  30. How should ignored pixels and classes absent from an image be handled when computing segmentation metrics?

  31. How many non-overlapping 16-by-16 patches come from a 224-by-224 image, and what changes if the image dimensions double?

  32. How would you use class, object size, lighting, and camera slices to investigate an aggregate vision score?

  33. How would you choose a classifier's decision threshold when missed defects and false alarms have different costs?

  34. What does confidence calibration measure, and why does a high confidence score not guarantee a correct prediction?

  35. How does tracking-by-detection associate object observations across frames, and how can occlusion break that association?

  36. How would you benchmark end-to-end vision inference without confusing throughput, model-only latency, and user-visible latency?

  37. What can post-training quantization change, and why must the quantized vision model be re-evaluated?

  38. What tests would you run after exporting a vision model to a different runtime?

  39. Which seeds, data artifacts, library versions, and runtime settings would you record to make an experiment reproducible?

  40. How would you detect inconsistent bounding boxes, class mappings, or mask annotations before training?

Computer Vision Interview Questions for Experienced

These experienced-level questions address dataset strategy, domain shift, uncertainty, architecture selection, inference constraints, monitoring, and system design. They ask how an engineer gathers evidence, manages trade-offs, and detects failures that a single aggregate benchmark can conceal.

  1. How would you decide whether a visual inspection problem needs classical image processing, classification, detection, or segmentation?

  2. How would you audit a surprisingly strong image-model result for duplicates, scene leakage, and preprocessing leakage?

  3. What should a dataset release record about provenance, permitted use, consent, coverage, and retention?

  4. With a fixed labeling budget, how would you balance uncertain examples, diverse examples, rare cases, and a representative evaluation set?

  5. How would you judge an apparent improvement on a rare class when the evaluation set contains very few independent examples?

  6. Two teams report different mAP for the same detector: how would you reconcile their evaluation pipelines?

  7. A model degrades after a camera or site change: how would you separate input-pipeline defects from distribution shift?

  8. How would you design robustness tests for blur, low light, compression, occlusion, and unusual viewpoints without claiming universal robustness?

  9. How would you investigate whether a model learned a background shortcut rather than the intended visual signal?

  10. How would you compare two vision architectures fairly when their training data, pretraining, image sizes, and inference budgets differ?

  11. What would a production image pipeline validate and monitor before passing data to a model?

  12. How would you allocate a 100-millisecond end-to-end budget across capture, preprocessing, inference, postprocessing, and communication?

  13. How would you roll out a new vision model using representative shadow or canary evaluation and a reversible versioned deployment?

  14. When would you prefer quantization-aware training over post-training quantization, and how would you choose representative calibration data?

  15. What numerical problems can mixed-precision vision training introduce, and how would you diagnose them?

  16. How would you reduce training memory use while checking the effects on convergence and experiment comparability?

  17. How do depthwise separable convolutions reduce arithmetic compared with a standard convolution, and why might latency not improve proportionally?

  18. How can distributed training or gradient accumulation change the effective batch and loss weighting for variable-sized image data?

  19. How would you distinguish difficult examples from incorrect labels before choosing a noise-handling strategy?

  20. When could self-supervised visual pretraining be useful, and how would you evaluate it without contaminating the downstream test set?

  21. How would you choose between a CNN and a vision transformer for a data-limited deployment with a fixed compute budget?

  22. What does a CLIP-style model make possible for text-guided image classification, and what must be tested before relying on zero-shot predictions?

  23. How would you evaluate a promptable segmentation model for a domain where prompts and mask quality vary?

  24. How does DETR's set prediction and bipartite matching differ from a detector that relies on duplicate removal with NMS?

  25. What changes when a detector predicts boxes without predefined anchors, and what design choices still remain?

  26. Why can ordinary NMS miss neighboring objects in crowded scenes, and how would you compare suppression alternatives?

  27. How would you evaluate segmentation of thin structures when good global overlap hides poor boundary quality?

  28. How would you choose between a homography, a fundamental matrix, and an essential matrix for two-view geometry?

  29. Why does stereo depth become sensitive to disparity error at long range, and how would you propagate a small disparity uncertainty?

  30. Which camera or image-pipeline changes require revisiting calibration, and how would you validate the updated geometry?

  31. How would you compare trackers when one detects more objects but causes more association errors?

  32. How would you reduce video-processing cost by sampling frames or tracking between detections without overlooking temporal failure modes?

  33. What calibration, coordinate-frame, and timing problems arise when combining camera images with depth or other sensors?

  34. How would you evaluate unknown or out-of-distribution inputs rather than assuming a classifier's highest softmax score detects them?

  35. How would you diagnose an OCR pipeline whose text recognition fails on skewed, low-resolution, or complex-layout images?

  36. How would you collect useful production diagnostics while minimizing retained images and sensitive visual information?

  37. How would you define an authorized defensive evaluation of a vision system's failure modes without treating one benchmark as a security guarantee?

  38. How would you design abstention and human review for uncertain predictions, including the operational cost of review?

  39. What can a saliency map suggest about a vision model, and why is it not proof of a faithful or causal explanation?

  40. What evidence should accompany a deployed vision model so another team can reproduce results, diagnose failures, and decide when to retrain or roll back?

Computer Vision Interview Questions and Answers

The answers follow the question bank in order and connect each method to its assumptions and limitations. Numerical examples define their inputs, while code examples identify relevant shapes, data types, layouts, and library context. Treat a correct calculation or a small test as evidence for that example, not as proof of model quality on unseen data.

Computer Vision Interview Questions and Answers for Beginners

The beginner answers explain the mechanism behind each operation and make conventions explicit. They connect image arrays to visual meaning, distinguish tasks and output types, and use small calculations to show why preprocessing and evaluation choices matter.

1. What distinguishes computer vision from image processing, and how can they work together?

Image processing changes or measures an image's pixels; computer vision uses visual data to infer something about a scene. Denoising, resizing, and contrast adjustment are image-processing operations. Recognizing a damaged package or locating a road marking is a computer-vision task. The boundary overlaps: a threshold-and-contour pipeline can perform useful vision without a neural network.

For a package-inspection system, processing might correct illumination and crop the inspection region before a classifier predicts damage. Those steps should be evaluated with the complete system, because smoothing can remove the very scratch being detected. A visually cleaner image is not automatically a more useful model input. The target decision, rather than whether an algorithm is learned, defines the practical goal.

2. How do image height, width, channels, and data type describe a digital image?

Height counts pixel rows, width counts pixel columns, and channels describe the values stored at each location. A NumPy color image commonly has shape (H, W, C); a grayscale image may have shape (H, W). Channel count alone does not establish whether the order is RGB or BGR. The dtype determines numerical representation: uint8 holds integers from 0 to 255, while float32 does not by itself imply a particular image range.

This synthetic RGB image has two rows and three columns. NumPy indexes the pixel at coordinates (x, y) as [y, x], with the origin at the top left.

Python example

import numpy as np

rgb = np.zeros((2, 3, 3), dtype=np.uint8)
rgb[0, 1] = [255, 0, 0]  # Red at x=1, y=0.
print(rgb.shape, rgb.dtype)  # (2, 3, 3) uint8
import numpy as np

rgb = np.zeros((2, 3, 3), dtype=np.uint8)
rgb[0, 1] = [255, 0, 0]  # Red at x=1, y=0.
print(rgb.shape, rgb.dtype)  # (2, 3, 3) uint8
import numpy as np

rgb = np.zeros((2, 3, 3), dtype=np.uint8)
rgb[0, 1] = [255, 0, 0]  # Red at x=1, y=0.
print(rgb.shape, rgb.dtype)  # (2, 3, 3) uint8

3. How much uncompressed pixel storage does a 640-by-480 three-channel uint8 image require?

Assuming width 640, height 480, three channels, and one byte per uint8 channel value, the pixel payload is 640 * 480 * 3 * 1 = 921,600 bytes. That is 900 KiB or approximately 0.879 MiB; in decimal units it is 0.9216 MB. RGB versus BGR does not change the storage requirement.

This calculation excludes array-object overhead, row padding in some image buffers, metadata, and additional working copies. A compressed JPEG or PNG file has a different, content-dependent size. Converting the same pixels to float32 requires four bytes per value, making the uncompressed payload 3,686,400 bytes.

Python example

import numpy as np

image = np.zeros((480, 640, 3), dtype=np.uint8)
assert image.nbytes == 921_600
assert image.astype(np.float32).nbytes == 3_686_400
import numpy as np

image = np.zeros((480, 640, 3), dtype=np.uint8)
assert image.nbytes == 921_600
assert image.astype(np.float32).nbytes == 3_686_400
import numpy as np

image = np.zeros((480, 640, 3), dtype=np.uint8)
assert image.nbytes == 921_600
assert image.astype(np.float32).nbytes == 3_686_400

4. Why can an image loaded with OpenCV have swapped red and blue colors in an RGB display?

OpenCV's conventional IMREAD_COLOR path decodes a three-channel image in BGR order. An RGB display interprets the first channel as red, so presenting those bytes without conversion exchanges red and blue. The pixels have not necessarily been corrupted; the producer and consumer disagree about their channel contract.

Convert once at the boundary, and keep the expected order explicit throughout preprocessing. This example requires a supplied local sample.png containing an ordinary 8-bit color image; the output remains (H, W, 3) with values in 0–255. Changing channel order does not perform model-specific scaling or standardization. Avoid a second conversion if another loader already returns RGB.

Python example

import cv2

bgr = cv2.imread("sample.png", cv2.IMREAD_COLOR)
if bgr is None:
    raise ValueError("Could not decode sample.png")
rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
import cv2

bgr = cv2.imread("sample.png", cv2.IMREAD_COLOR)
if bgr is None:
    raise ValueError("Could not decode sample.png")
rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
import cv2

bgr = cv2.imread("sample.png", cv2.IMREAD_COLOR)
if bgr is None:
    raise ValueError("Could not decode sample.png")
rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)

5. When might grayscale or HSV be more useful than RGB, and what information can be lost?

Grayscale is useful when shape, edges, or intensity matter more than color. It reduces a three-channel image to one channel, but different colors can collapse to similar intensities, making color-dependent distinctions impossible. OpenCV's standard RGB-to-gray conversion uses a weighted channel combination, not a simple average.

HSV separates hue, saturation, and value, which can make rules for a colored marker easier to express. It is not inherently invariant to lighting: shadows, highlights, and low saturation can still make hue unreliable. Standard OpenCV 8-bit HSV uses hue values 0–179 and saturation/value 0–255; floating-point conventions differ. RGB-to-HSV is principally a reparameterization, although quantization can lose precision. Retaining only hue or discarding saturation/value loses additional information.

6. How does scaling pixel values to a range differ from standardizing them with a mean and standard deviation?

Range scaling changes units, such as mapping an 8-bit value x to x / 255 in [0, 1]. Standardization subtracts a reference mean and divides by a reference standard deviation: z = (x - mean) / std. Standardized values are not restricted to [0, 1], and a deployment dataset need not end up with exactly zero mean or unit variance.

Use the preprocessing specified for the pretrained weights, or estimate statistics from the training split only. The example uses illustrative statistics for one channel, not a universal model recipe. Casting precedes arithmetic so the operation is not performed in an unsigned integer dtype.

Python example

import numpy as np

pixels = np.array([0, 128, 255], dtype=np.uint8)
scaled = pixels.astype(np.float32) / 255.0
standardized = (scaled - 0.5) / 0.25
# Approximately [-2.0, 0.00784, 2.0].
import numpy as np

pixels = np.array([0, 128, 255], dtype=np.uint8)
scaled = pixels.astype(np.float32) / 255.0
standardized = (scaled - 0.5) / 0.25
# Approximately [-2.0, 0.00784, 2.0].
import numpy as np

pixels = np.array([0, 128, 255], dtype=np.uint8)
scaled = pixels.astype(np.float32) / 255.0
standardized = (scaled - 0.5) / 0.25
# Approximately [-2.0, 0.00784, 2.0].

7. What trade-offs arise when resizing an image without preserving its aspect ratio?

Resizing width and height by different factors distorts shapes: circles become ellipses and object proportions change. That can undermine measurements or a model that relies on geometry. It does provide a simple fixed-size input and uses the entire destination canvas, so direct resizing can still be an intentional choice when training and deployment use the same policy.

Aspect-ratio-preserving alternatives have their own costs. Letterboxing adds padding, while resizing followed by cropping can remove important objects. For a 640-by-480 image fitted into a 224-by-224 canvas, uniform scaling gives 224-by-168 content and 56 total padding rows. Record the scale and padding offsets so boxes and keypoints can be transformed consistently and predictions mapped back to the original image.

8. Why should categorical segmentation masks usually be resized differently from photographs?

Photographs contain intensity or color measurements, so interpolation can blend nearby values to estimate a resized pixel. A categorical segmentation mask stores class IDs, which are names encoded as integers. Averaging labels 0 and 2 can create label 1 even when that class was absent. Nearest-neighbor resizing avoids invented IDs, although very small regions can still disappear during downsampling.

The example uses a two-dimensional uint8 mask with IDs 0 and 2. OpenCV's destination size is (width, height), unlike NumPy's (height, width) shape. Apply the same spatial transform to the associated photograph, but choose interpolation appropriate to each data type. Soft probabilities and continuous depth maps require different treatment from categorical labels.

Python example

import cv2
import numpy as np

mask = np.array([[0, 0], [2, 2]], dtype=np.uint8)
resized = cv2.resize(mask, (4, 4), interpolation=cv2.INTER_NEAREST)
assert set(np.unique(resized)) == {0, 2}
import cv2
import numpy as np

mask = np.array([[0, 0], [2, 2]], dtype=np.uint8)
resized = cv2.resize(mask, (4, 4), interpolation=cv2.INTER_NEAREST)
assert set(np.unique(resized)) == {0, 2}
import cv2
import numpy as np

mask = np.array([[0, 0], [2, 2]], dtype=np.uint8)
resized = cv2.resize(mask, (4, 4), interpolation=cv2.INTER_NEAREST)
assert set(np.unique(resized)) == {0, 2}

9. How do mean, Gaussian, and median filtering differ when reducing image noise?

A mean filter gives equal weight to pixels in a neighborhood. A Gaussian filter uses distance-dependent weights, emphasizing nearby pixels and producing controlled smoothing. Both are linear filters that can reduce fluctuating noise but also soften edges. A median filter selects the neighborhood's middle value; this nonlinear operation is often useful for isolated bright or dark impulses without averaging them into neighboring pixels.

Choose the filter and neighborhood size for the noise and the detail that must survive. The example introduces an isolated bright impulse into a constant, single-channel uint8 image in the range 0–255. Median filtering removes this particular impulse, but that does not establish that it is best for every noise distribution.

Python example

import cv2
import numpy as np

image = np.full((7, 7), 80, dtype=np.uint8)
image[3, 3] = 255
mean = cv2.blur(image, (3, 3))
gaussian = cv2.GaussianBlur(image, (3, 3), 0)
median = cv2.medianBlur(image, 3)
assert median[3, 3] == 80
import cv2
import numpy as np

image = np.full((7, 7), 80, dtype=np.uint8)
image[3, 3] = 255
mean = cv2.blur(image, (3, 3))
gaussian = cv2.GaussianBlur(image, (3, 3), 0)
median = cv2.medianBlur(image, 3)
assert median[3, 3] == 80
import cv2
import numpy as np

image = np.full((7, 7), 80, dtype=np.uint8)
image[3, 3] = 255
mean = cv2.blur(image, (3, 3))
gaussian = cv2.GaussianBlur(image, (3, 3), 0)
median = cv2.medianBlur(image, 3)
assert median[3, 3] == 80

10. What does an image edge represent, and why can an edge detector respond strongly to noise?

An image edge is a strong local change in intensity or color. It may correspond to an object boundary, but it can also come from a shadow, texture, reflection, or illumination change. Gradient operators estimate this change along image axes; a common magnitude is sqrt(gx * gx + gy * gy).

Noise also creates rapid pixel-to-pixel variation, so differentiation can produce large responses where no meaningful boundary exists. Smoothing before edge detection reduces that sensitivity, at the cost of potentially hiding fine structures. Canny combines gradient estimation with thinning and threshold-based connectivity. For diagnostic Sobel gradients, use a signed or floating-point output such as CV_32F; an unsigned output cannot represent negative directional responses correctly.

11. How do global, adaptive, and Otsu thresholding choose a foreground mask?

Global thresholding applies one threshold to the entire grayscale image. Adaptive thresholding computes a local threshold, making it useful when illumination varies across the image. Otsu's method chooses a global threshold from the intensity distribution by minimizing weighted within-class variance, equivalently maximizing between-class variance for the two groups. It often works well when foreground and background form distinct intensity populations, but a useful semantic split is not guaranteed.

Here, values above the selected threshold become foreground 255 and the rest become background 0. The input is a synthetic, single-channel uint8 image. Dark foreground on a bright background may instead require inverse thresholding.

Python example

import cv2
import numpy as np

gray = np.array([[15, 20, 25], [210, 220, 230]], dtype=np.uint8)
threshold, mask = cv2.threshold(
    gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU
)
assert mask.tolist() == [[0, 0, 0], [255, 255, 255]]
import cv2
import numpy as np

gray = np.array([[15, 20, 25], [210, 220, 230]], dtype=np.uint8)
threshold, mask = cv2.threshold(
    gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU
)
assert mask.tolist() == [[0, 0, 0], [255, 255, 255]]
import cv2
import numpy as np

gray = np.array([[15, 20, 25], [210, 220, 230]], dtype=np.uint8)
threshold, mask = cv2.threshold(
    gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU
)
assert mask.tolist() == [[0, 0, 0], [255, 255, 255]]

12. What do erosion, dilation, opening, and closing do to a binary foreground region?

For a binary mask with white foreground, erosion shrinks foreground regions and dilation expands them according to a structuring element. Opening performs erosion followed by dilation; it can remove small foreground specks or narrow connections. Closing performs dilation followed by erosion; it can fill small background gaps or join nearby foreground regions.

The kernel's shape and size determine which structures change. These operations are not harmless cleanup: opening may delete a thin genuine object, and closing may merge distinct objects. Specify foreground polarity and inspect border behavior. The example removes a one-pixel speck while retaining a larger square in a two-dimensional uint8 mask whose values are 0 and 255.

Python example

import cv2
import numpy as np

mask = np.zeros((9, 9), dtype=np.uint8)
mask[3:7, 3:7] = 255
mask[1, 1] = 255
kernel = np.ones((3, 3), dtype=np.uint8)
opened = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
assert opened[1, 1] == 0
import cv2
import numpy as np

mask = np.zeros((9, 9), dtype=np.uint8)
mask[3:7, 3:7] = 255
mask[1, 1] = 255
kernel = np.ones((3, 3), dtype=np.uint8)
opened = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
assert opened[1, 1] == 0
import cv2
import numpy as np

mask = np.zeros((9, 9), dtype=np.uint8)
mask[3:7, 3:7] = 255
mask[1, 1] = 255
kernel = np.ones((3, 3), dtype=np.uint8)
opened = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
assert opened[1, 1] == 0

13. What can an intensity histogram reveal, and what can histogram equalization change?

An intensity histogram counts how many pixels fall into each intensity bin. For an 8-bit grayscale image, concentrations near 0 suggest dark values, concentrations near 255 suggest bright values, and a narrow occupied range can indicate limited contrast. A histogram discards spatial arrangement, so two visibly different images can have the same histogram. A dark histogram alone does not prove incorrect exposure.

Histogram equalization remaps intensities using their cumulative distribution to spread frequently occupied values across more of the output range. It can reveal contrast but cannot recover detail lost through clipping, and it can amplify noise. For color images, equalizing RGB channels independently may change colors. A luminance-oriented conversion or contrast-limited adaptive equalization may be more suitable, subject to task-specific validation.

14. What does a learned convolutional filter compute in a CNN?

A learned convolutional filter computes weighted sums of local input patches, typically adds a bias, and repeats that operation across spatial locations using the same weights. In a standard multi-channel layer, each output channel combines contributions from all input channels. Training adjusts the weights to reduce the task loss; the filters are not necessarily recognizable edge detectors.

For one input channel, a 3-by-3 kernel uses nine weights per output channel, plus an optional bias. Applied to a floating-point feature map, those weights can respond to a particular local pattern. Framework layers commonly implement cross-correlation rather than explicitly reversing the kernel as in mathematical convolution. An activation function usually follows to introduce nonlinearity; the weighted-sum operation alone is affine.

15. How do kernel size, stride, and padding change a convolution layer's output shape?

Kernel size controls the spatial footprint, stride controls the step between output positions, and padding adds a border around the input. For one spatial dimension with symmetric padding, the output size is floor((input + 2*padding - dilation*(kernel - 1) - 1) / stride) + 1. Apply the calculation independently to height and width.

For a 32-by-32 input, a 3-by-3 kernel with stride 2, padding 1, and dilation 1 produces 16-by-16 output. The batch size is unchanged, while output channels are chosen separately. In PyTorch's usual batched layout, (N, 3, 32, 32) becomes (N, C_out, 16, 16) for a layer with three input channels. Padding preserves spatial size only under appropriate kernel, dilation, and stride choices.

Python example

import math

size = math.floor((32 + 2 * 1 - 1 * (3 - 1) - 1) / 2) + 1
assert size == 16
import math

size = math.floor((32 + 2 * 1 - 1 * (3 - 1) - 1) / 2) + 1
assert size == 16
import math

size = math.floor((32 + 2 * 1 - 1 * (3 - 1) - 1) / 2) + 1
assert size == 16

16. Why might a CNN use pooling or a strided convolution to reduce spatial resolution?

Downsampling reduces the number of spatial positions processed by later layers, which can lower computation and activation memory. It also lets later features summarize larger portions of the original image. Max pooling retains a local maximum; average pooling summarizes a neighborhood. A strided convolution learns the combination used while moving across the input in larger steps.

The cost is lost spatial detail. Tiny objects, narrow boundaries, and precise locations may disappear, and downsampling can introduce aliasing. Pooling does not guarantee invariance to translation, nor does a learned downsampler guarantee that useful detail survives. Classification can often tolerate stronger spatial reduction than segmentation, where skip connections or higher-resolution features help preserve localization. The appropriate schedule depends on object size and the task's required precision.

17. Why are nonlinear activation functions needed between learned linear layers?

Without nonlinear activations, composing learned linear or affine layers still produces an affine mapping. For example, W2 * (W1 * x + b1) + b2 can be rewritten as one matrix multiplication plus a bias. Adding more such layers therefore does not, by itself, create nonlinear decision boundaries.

An activation such as ReLU, max(0, x), changes how different input regions are represented, allowing a network to model more complex relationships. ReLU also has zero gradient for negative inputs, so units can become inactive during training. Alternatives have different smoothness and gradient properties. Output activation is a separate decision: a loss that expects logits should receive raw scores rather than an extra softmax or sigmoid applied out of habit.

18. What does overfitting look like in training and validation results for an image classifier?

Overfitting occurs when a model becomes better at fitting its training examples without improving its performance on independent examples. A typical pattern is falling training loss while validation loss reaches a minimum and then rises; validation accuracy may plateau while training accuracy continues increasing. A gap is a warning signal, not conclusive proof on its own.

Check that evaluation uses the correct model mode, comparable preprocessing, accurate labels, and genuinely independent validation data. Training augmentation and dropout can make training metrics look worse than validation metrics even without a problem. Remedies can include more representative data, appropriate augmentation, reduced model capacity, regularization, or early stopping. Select those changes with validation results rather than repeatedly using the held-out test set as feedback.

19. How can data augmentation help a vision model, and when can an augmentation invalidate a label?

Data augmentation creates varied training examples from existing ones, encouraging the model to tolerate changes that should not affect the intended prediction. Moderate shifts, crops, blur, or brightness variation may resemble real capture conditions, but each transformation needs a label-preservation argument.

A horizontal flip can invalidate a left-versus-right label; rotating a digit may change its meaning; a crop can remove the only object that justified an image-level class. For detection and segmentation, spatial transformations must update boxes and masks together with the image. Color changes are inappropriate when exact color defines the target. Apply random training augmentation after the dataset split, keep evaluation preprocessing controlled, and compare performance on representative original images rather than assuming that more augmentation is always better.

20. Why should related images be kept together when creating train, validation, and test splits?

Related images can share information that makes evaluation artificially easy. Adjacent video frames, multiple views of one physical object, and augmented copies of one photograph are not independent examples. Randomly splitting individual files can let a model recognize familiar backgrounds or objects instead of generalizing to new ones.

Choose the grouping unit that matches deployment. If the system must handle previously unseen manufactured parts, keep every view of each part in one split; if it must handle new sites, consider holding out complete sites. Perform grouping and duplicate checks before augmentation. Stratification can help preserve class proportions, but it must not break the independence boundary. Report the number of independent groups, because thousands of near-identical frames may contain much less evaluation evidence than their image count suggests.

21. How do image-level classes, bounding boxes, and pixel masks differ as training labels?

An image-level label describes the whole image, such as whether a package is damaged, without locating the evidence. A bounding box adds a rectangular location for an object, usually with a class label and one box per annotated instance. A pixel mask gives finer spatial supervision by marking which pixels belong to a class or instance.

These labels support different questions: classification asks what is present, detection also asks where and how many, and segmentation asks which pixels belong to the target. Masks generally require more detailed annotation than boxes, but annotation effort varies with tooling and image complexity. Define conventions for occlusion, truncated objects, background, and ignored regions. A missing annotation must not automatically be interpreted as verified absence of an object.

22. Why do convolutional layers generally use fewer parameters than fully connected layers applied to all image pixels?

Convolutions exploit local connectivity and weight sharing: the same small filter is reused at many image positions. A fully connected layer gives each output unit its own weight for every input value. For an ordinary convolution with no groups, the parameter count is (kernel_height * kernel_width * input_channels + 1) * output_channels when biases are included. It does not grow with image height or width.

A 3-by-3 convolution from 3 to 16 channels has (3 * 3 * 3 + 1) * 16 = 448 parameters. A dense layer mapping all 32-by-32 RGB pixels to 16 units has (32 * 32 * 3 + 1) * 16 = 49,168. These layers produce different output structures: feature maps versus one vector. Fewer parameters also does not automatically mean fewer operations, since convolution reuses them repeatedly.

23. How does using a pretrained model as a feature extractor differ from fine-tuning it?

A fixed feature extractor keeps the pretrained backbone unchanged and trains a new task-specific head on its representations. Fine-tuning updates some or all backbone weights as well, allowing the features to adapt to the new data. Feature extraction is a useful baseline when labels or compute are limited; fine-tuning offers more flexibility but can overfit or damage useful pretrained representations.

A common sequence is to train the new head first, then unfreeze selected layers with a smaller learning rate and validate the change. Preserve the preprocessing expected by the pretrained weights. Freezing parameters and selecting evaluation mode are separate concepts in PyTorch: BatchNorm running statistics can still change in training mode even when its trainable parameters have gradients disabled. Decide that behavior deliberately.

24. How do single-label and multilabel image classification differ?

Single-label classification assigns exactly one class from a defined set to each image. For example, one package might be classified as intact, dented, or torn when the labeling policy makes those classes mutually exclusive. Multilabel classification allows several labels simultaneously, such as dented and wet, and can allow none.

A common PyTorch single-label setup uses logits of shape (N, C), integer class targets of shape (N,), and CrossEntropyLoss. A multilabel setup commonly uses (N, C) logits, floating-point binary targets of the same shape, and BCEWithLogitsLoss. These losses already incorporate the necessary log-softmax or sigmoid-related computation, so do not apply those activations first. At inference, multilabel decisions use per-class sigmoid scores and chosen thresholds rather than a single argmax.

25. What extra predictions must an object detector make beyond an image classifier?

An image classifier predicts an image-level class or set of classes. An object detector also predicts locations and associates classes with individual object instances, allowing multiple objects of the same category in one image. A typical output contains bounding boxes, class labels, and confidence scores, with a variable number of retained detections per image.

The model must learn both localization and recognition. Depending on the architecture, training can involve box regression, classification, objectness, or matching objectives. Evaluation must check spatial agreement and one-to-one matching with annotated objects; predicting the right category somewhere in the image is insufficient. Duplicate detections and missed small objects are distinct failure modes. A confidence score also should not automatically be interpreted as a calibrated probability of correctness.

26. How do semantic, instance, and panoptic segmentation describe a scene differently?

Semantic segmentation assigns a category to each pixel without distinguishing separate objects of the same category. If two bicycles touch, both can simply receive the bicycle label. Instance segmentation separates individual countable objects, producing a distinct mask for each bicycle as well as its class.

Panoptic segmentation combines semantic coverage with instance separation: countable “thing” categories receive individual instance IDs, while uncountable “stuff” categories such as sky or road receive category regions. A panoptic output assigns each valid pixel one category and, where relevant, an instance identity. An ordinary collection of instance masks does not necessarily cover the whole scene and may overlap. Annotation policies must therefore specify category definitions, occlusions, and any void or ignored pixels before results can be compared.

27. What must be specified before interpreting four numbers as a bounding box?

Four numbers need a format, coordinate system, units, and image reference before they define a box. Common formats include (x_min, y_min, x_max, y_max), (x, y, width, height), and (center_x, center_y, width, height). Coordinates may be absolute pixels or normalized fractions, and may refer to the original image or a resized, padded input.

For continuous xyxy coordinates with a top-left origin, x increasing rightward and y downward, (10, 20, 30, 50) has width 20, height 30, and area 600. Do not add one to widths unless the annotation format explicitly uses inclusive integer endpoints. Check ordering, image bounds, and positive area. NumPy cropping instead indexes rows before columns, so the corresponding half-open integer crop is image[20:50, 10:30].

28. What is intersection over union, and what is its value when two boxes each have area 100 and overlap by 50?

Intersection over union measures spatial overlap as IoU = intersection_area / union_area, where union_area = area_A + area_B - intersection_area. Here, the union is 100 + 100 - 50 = 150, giving IoU = 50 / 150 = 1/3, approximately 0.333. Dividing by 100 would measure a different overlap ratio, not IoU.

For valid positive-area boxes, IoU ranges from 0 for no overlap to 1 for identical boxes. Both boxes must use the same coordinates and area convention. A detection is not automatically correct merely because its IoU is positive: evaluation also specifies an overlap threshold, class agreement, and matching rules. Degenerate boxes with zero union need an explicit rejection or handling policy rather than uncontrolled division by zero.

29. What do true positives, false positives, false negatives, and true negatives mean for a binary image classifier?

First define the positive class. If “defective” is positive, a true positive is a defective image predicted defective, while a false negative is a defective image predicted normal. A false positive is a normal image predicted defective, and a true negative is a normal image predicted normal. These counts depend on the score threshold used to turn predictions into decisions.

Actual image

Predicted defective

Predicted normal

Defective

True positive

False negative

Normal

False positive

True negative

The table's axis labels matter because libraries do not all display confusion matrices with the same conventions. Counts describe different operational errors: false positives create unnecessary inspection, while false negatives let defects pass. This image-classification interpretation does not directly supply a meaningful true-negative count for object detection.

30. How do precision and recall emphasize different kinds of classification error?

Precision asks how many positive predictions were correct: precision = TP / (TP + FP). Recall asks how many actual positives were found: recall = TP / (TP + FN). Precision emphasizes false alarms; recall emphasizes missed positives. Neither includes true negatives in its denominator.

For 40 true positives, 10 false positives, and 20 false negatives, precision is 40 / 50 = 0.80, while recall is 40 / 60, approximately 0.667. Lowering a decision threshold can increase recall by accepting more cases, often at the expense of precision. Choose a threshold using validation data and the cost of errors, then report it with the metrics. If a denominator is zero, state the evaluation policy explicitly rather than silently presenting an undefined value as good performance.

31. Why can a classifier with high accuracy still be poor at finding a rare visual defect?

Accuracy averages correctness across all examples, so the majority class can dominate it. In a dataset of 10,000 images with 100 defective examples, a classifier that always predicts “normal” achieves 99% accuracy while finding no defects. Its defect recall is 0 / 100 = 0, and its precision is undefined because it makes no positive predictions.

Inspect the confusion matrix, defect-class precision and recall, and performance across relevant defect types. Precision-recall analysis can be more informative than accuracy when positives are rare, but the evaluation set must reflect the intended operating conditions. A balanced training sampler does not make production prevalence balanced. Select the operating threshold based on tolerated misses and review capacity, and report how many actual defects support the measured result.

32. What separate roles do the training, validation, and test datasets play?

Training data supplies examples used to update model parameters. Validation data supports choices such as architecture, augmentation, learning rate, early stopping, and decision threshold. The test set estimates performance after those choices are fixed; repeatedly tuning against it turns it into another validation set.

Split data before fitting learned preprocessing statistics, and fit those statistics on training data only. Keep related images and duplicates within the same partition so the measured generalization matches the deployment question. The test set should represent the population or conditions for which a claim is made, and its size should support meaningful estimates. Cross-validation can help use limited development data, but each fold still needs leakage-safe preprocessing and appropriate grouping. It does not justify reusing a supposedly untouched final test set for model selection.

33. Why is the training loss not necessarily the metric used to select a useful vision model?

A training loss is a mathematical objective used to update parameters, usually chosen partly because it provides useful gradients. A deployment metric describes how well the system meets a practical goal. Cross-entropy, for example, depends on the probability assigned to the true class, whereas thresholded accuracy depends only on which class is selected.

Two models can therefore have similar accuracy but different loss, or lower loss without better recall at the required false-alarm rate. Detection and segmentation also combine objectives that do not exactly match their final overlap-based metrics. Select checkpoints with a prespecified validation criterion tied to the application, while tracking loss for optimization diagnostics. Keep evaluation thresholds and preprocessing fixed when comparing candidates, and confirm the chosen system once on held-out test data.

34. How does running a trained model for inference differ from training it?

Training computes predictions, compares them with targets, propagates gradients, and updates parameters through an optimizer. Inference applies an already trained model to produce outputs without that learning step. It still requires the same input contract, including channel order, spatial size, dtype, and normalization.

In PyTorch, model.eval() changes the behavior of modules such as dropout and BatchNorm; it does not disable gradient recording. torch.inference_mode() disables autograd-related work but does not select evaluation mode. Use both for ordinary inference. This snippet assumes a loaded classifier and a correctly preprocessed floating-point batch in (N, C, H, W) layout on the same device. Its returned logits still need task-appropriate interpretation.

Python example

import torch

def predict_logits(model, batch):
    model.eval()
    with torch.inference_mode():
        return model(batch)
import torch

def predict_logits(model, batch):
    model.eval()
    with torch.inference_mode():
        return model(batch)
import torch

def predict_logits(model, batch):
    model.eval()
    with torch.inference_mode():
        return model(batch)

35. What is the difference between detecting an image keypoint and describing it?

A keypoint detector chooses repeatable image locations, such as corners or distinctive blobs, and may attach scale, orientation, and a response score. A descriptor encodes the appearance around a chosen location so that it can be compared with locations in another image. Detection answers where to sample; description answers how to represent the sampled neighborhood.

Matching descriptors produces candidate correspondences, not guaranteed geometric truth. Repeated patterns, viewpoint changes, blur, or lighting can create ambiguous matches. A matching metric must suit the descriptor: binary descriptors commonly use Hamming distance, while floating-point descriptors often use Euclidean distance. For tasks such as aligning two views of a flat poster, geometric verification can reject inconsistent matches. No keypoints or no usable descriptors is also a valid outcome that code must handle.

36. How do translation, rotation, scaling, and perspective changes transform an image?

Translation shifts points, rotation turns them around a chosen center, and scaling changes distances along one or both axes. Uniform scaling preserves proportions; unequal axis scaling does not. These operations can be expressed as affine transforms, which preserve parallel lines. A perspective transform is more general: it can map a rectangle to a quadrilateral and make parallel lines converge.

With image coordinates x rightward and y downward, record the transform direction, rotation center, and output canvas explicitly. OpenCV uses a 2-by-3 matrix for warpAffine and a 3-by-3 matrix for warpPerspective. Resampling also requires interpolation and border choices. A single homography describes a plane's perspective relationship, or pure camera rotation under the usual camera assumptions; it cannot generally align all depths in a scene with camera translation.

37. What do camera intrinsics and extrinsics describe in the pinhole camera model?

Camera intrinsics describe projection from camera coordinates into image coordinates: focal lengths (fx, fy) in pixel units, the principal point (cx, cy), and, in a general matrix, skew. Extrinsics describe rotation and translation between a world frame and the camera frame. With the world-to-camera convention, X_camera = R * X_world + t; the translation vector is not directly the camera's world position.

For zero skew and a camera-frame point (Xc, Yc, Zc) in front of an ideal camera, pixel coordinates are u = fx * Xc / Zc + cx and v = fy * Yc / Zc + cy. OpenCV's usual camera axes point right, down, and forward. Lens-distortion coefficients extend the ideal pinhole model and are separate from the intrinsic matrix. Resizing or cropping an image changes the corresponding pixel-coordinate intrinsics, so calibration must match the actual image pipeline.

38. What does optical flow estimate, and how is it different from identifying an object?

Optical flow estimates apparent image motion between frames, usually as a two-dimensional displacement field or displacements at selected points. In a forward-flow convention, a point at (x, y) in the first frame corresponds approximately to (x + dx, y + dy) in the second. With x rightward and y downward, positive dy means downward image motion. State the frame interval if converting displacement into velocity.

Flow does not determine an object's category or persistent identity. Motion can come from the camera as well as the scene. Occlusion, weak texture, repeated patterns, large displacement, and illumination changes can make estimates unreliable. Classical methods often assume approximate brightness consistency and locally coherent motion. Detection and tracking can use flow, but they add semantic and association decisions that flow alone does not provide.

39. What privacy questions should be asked before collecting images for a vision dataset?

Start with purpose and necessity: what decision requires the images, and could less sensitive data support it? Establish who collected the images, whether the intended use is authorized, what notice or consent is appropriate, and whether licensing permits the planned training and redistribution. Public availability alone does not settle those questions.

Check for people, identifying text, location clues, sensitive settings, and revealing metadata, including information incidental to the target task. Define access controls, retention periods, deletion procedures, and whether raw images need to be retained at all. Redaction can reduce exposure but may leave identifying context. Document collection conditions, coverage gaps, and restrictions in dataset records. Escalate context-specific privacy or legal questions to qualified reviewers before collection, rather than treating model development as permission to gather everything available.

40. Why must a deployed vision model be evaluated for latency and memory as well as predictive quality?

A model can be predictively useful yet unsuitable for deployment if it responds too slowly or exceeds available memory. Latency affects whether a decision arrives in time, while memory includes weights, intermediate activations, input buffers, and runtime workspace. A small model file does not establish low peak memory, especially with large images or batches.

Measure the complete path where relevant: decoding, preprocessing, data transfer, model execution, postprocessing, and communication. Report hardware, runtime, input size, precision, batch size, warmup, and concurrent load so measurements are interpretable. Distinguish per-request latency from throughput, and inspect tail latency rather than only the mean. Accelerators may execute asynchronously, requiring synchronization or an appropriate timing tool. Compare predictive quality and resource use together on representative inputs instead of assuming operation counts predict real latency.

Computer Vision Interview Questions and Answers for Intermediate

The intermediate answers explain design choices and trace their consequences through training or inference. They distinguish model errors from data and evaluation problems, identify common shape or coordinate assumptions, and compare alternatives without assuming one architecture wins in every setting.

41. How would you write an OpenCV image-loading step that checks failure, channel order, shape, and value range before inference?

Make the decoder's contract explicit rather than assuming that every file produces an RGB tensor. This example deliberately converts decodable images to three-channel, 8-bit BGR, then produces contiguous RGB float32 data with shape (1, 3, H, W) and values in [0, 1].

Python example (OpenCV)

import cv2
import numpy as np

def load_rgb(path):
    bgr = cv2.imread(str(path), cv2.IMREAD_COLOR)
    if bgr is None or bgr.size == 0:
        raise ValueError("Image could not be decoded")
    if bgr.ndim != 3 or bgr.shape[2] != 3:
        raise ValueError("Expected HWC with three channels")
    if bgr.dtype != np.uint8:
        raise ValueError("Expected 8-bit decoded pixels")
    rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
    x = rgb.astype(np.float32) / np.float32(255.0)
    if not np.isfinite(x).all() or x.min() < 0 or x.max() > 1:
        raise ValueError("Invalid input values")
    return np.ascontiguousarray(x.transpose(2, 0, 1)[None])
import cv2
import numpy as np

def load_rgb(path):
    bgr = cv2.imread(str(path), cv2.IMREAD_COLOR)
    if bgr is None or bgr.size == 0:
        raise ValueError("Image could not be decoded")
    if bgr.ndim != 3 or bgr.shape[2] != 3:
        raise ValueError("Expected HWC with three channels")
    if bgr.dtype != np.uint8:
        raise ValueError("Expected 8-bit decoded pixels")
    rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
    x = rgb.astype(np.float32) / np.float32(255.0)
    if not np.isfinite(x).all() or x.min() < 0 or x.max() > 1:
        raise ValueError("Invalid input values")
    return np.ascontiguousarray(x.transpose(2, 0, 1)[None])
import cv2
import numpy as np

def load_rgb(path):
    bgr = cv2.imread(str(path), cv2.IMREAD_COLOR)
    if bgr is None or bgr.size == 0:
        raise ValueError("Image could not be decoded")
    if bgr.ndim != 3 or bgr.shape[2] != 3:
        raise ValueError("Expected HWC with three channels")
    if bgr.dtype != np.uint8:
        raise ValueError("Expected 8-bit decoded pixels")
    rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
    x = rgb.astype(np.float32) / np.float32(255.0)
    if not np.isfinite(x).all() or x.min() < 0 or x.max() > 1:
        raise ValueError("Invalid input values")
    return np.ascontiguousarray(x.transpose(2, 0, 1)[None])

This is not universal pretrained-model preprocessing: apply that model's specified resizing, cropping, and normalization separately. An explicit color decode discards alpha and may reduce higher-bit-depth input; reject those formats earlier if preserving them matters. Also bound file size and decoded dimensions in a production service.

42. Why can arithmetic on uint8 images wrap or saturate, and how would you safely compute an image difference?

A uint8 array can represent only integers from 0 through 255. NumPy arithmetic between such arrays ordinarily retains that dtype, so subtraction can wrap: a negative difference becomes a large positive value. OpenCV operations such as cv2.subtract instead saturate unsigned output at zero, which still loses the sign.

Cast before subtracting to preserve signed differences. For two aligned, same-shaped uint8 images:

Python example (NumPy)

import numpy as np

if a.shape != b.shape or a.dtype != np.uint8 or b.dtype != np.uint8:
    raise ValueError("Expected matching uint8 images")
difference = a.astype(np.int16) - b.astype(np.int16)
absolute_difference = np.abs(difference).astype(np.uint8)
import numpy as np

if a.shape != b.shape or a.dtype != np.uint8 or b.dtype != np.uint8:
    raise ValueError("Expected matching uint8 images")
difference = a.astype(np.int16) - b.astype(np.int16)
absolute_difference = np.abs(difference).astype(np.uint8)
import numpy as np

if a.shape != b.shape or a.dtype != np.uint8 or b.dtype != np.uint8:
    raise ValueError("Expected matching uint8 images")
difference = a.astype(np.int16) - b.astype(np.int16)
absolute_difference = np.abs(difference).astype(np.uint8)

The signed result lies in [-255, 255]; its magnitude fits uint8. Cast to float before squaring differences or accumulating other operations that could exceed int16. To compare content meaningfully, verify channel order, geometric alignment, exposure, and numeric range first. Casting after the subtraction cannot recover values already lost to wrapping or clipping.

43. A pretrained classifier works in a notebook but fails in an API: how would you check for preprocessing mismatch?

Run one fixed image through both paths and compare intermediate arrays before comparing predictions. Check decoder behavior, image orientation, RGB versus BGR, alpha handling, resize dimensions, aspect-ratio policy, crop coordinates, interpolation, and antialiasing. A visually similar preview can hide a material tensor difference.

At the model boundary, record shape, dtype, layout, per-channel minimum and maximum, and normalization parameters. Check for double division by 255, missing normalization, or applying statistics in the wrong channel order. Confirm identical weights, class-index mappings, evaluation mode, and output interpretation: logits are not probabilities.

Use a small golden set that includes portrait, landscape, grayscale, and unusual-size inputs. Compare tensors and logits with an agreed tolerance, then decoded labels. If tensors match but outputs diverge, investigate runtime precision, export behavior, and unsupported operators. Package preprocessing with the model instead of maintaining two independent implementations.

44. How would you apply the same random geometric augmentation to an image, its boxes, and its segmentation mask?

Sample a geometric transform once and apply its parameters to every spatial target. Independently calling a random transform for the image and annotations can silently produce different crops or flips. For example, assume an HWC image, an HW class-ID mask, and float boxes in continuous pixel-edge xyxy coordinates:

Python example (NumPy)

# image, boxes, mask, and a NumPy Generator rng are inputs.
height, width = image.shape[:2]
if mask.shape != (height, width):
    raise ValueError("Mask and image dimensions differ")
if rng.random() < 0.5:
    image = image[:, ::-1].copy()
    mask = mask[:, ::-1].copy()
    flipped = boxes.copy()
    flipped[:, 0] = width - boxes[:, 2]
    flipped[:, 2] = width - boxes[:, 0]
    boxes = flipped
# image, boxes, mask, and a NumPy Generator rng are inputs.
height, width = image.shape[:2]
if mask.shape != (height, width):
    raise ValueError("Mask and image dimensions differ")
if rng.random() < 0.5:
    image = image[:, ::-1].copy()
    mask = mask[:, ::-1].copy()
    flipped = boxes.copy()
    flipped[:, 0] = width - boxes[:, 2]
    flipped[:, 2] = width - boxes[:, 0]
    boxes = flipped
# image, boxes, mask, and a NumPy Generator rng are inputs.
height, width = image.shape[:2]
if mask.shape != (height, width):
    raise ValueError("Mask and image dimensions differ")
if rng.random() < 0.5:
    image = image[:, ::-1].copy()
    mask = mask[:, ::-1].copy()
    flipped = boxes.copy()
    flipped[:, 0] = width - boxes[:, 2]
    flipped[:, 2] = width - boxes[:, 0]
    boxes = flipped

Here box edges use width, not width - 1. Cropping also requires clipping boxes, removing invalid instances, and updating aligned labels. Use label-preserving nearest-neighbor interpolation for categorical masks; photometric changes affect images only. Finally, verify that the augmentation preserves the task's meaning: flipping text or directional categories may require relabeling or exclusion.

45. How can border handling and output data type change the result of an image filter?

A filter needs values outside the image whenever its kernel overlaps a boundary. Zero padding, edge replication, reflection, and other extensions supply different neighborhoods, so identical kernels can give different border responses. Explicitly record the border mode rather than relying on a library default, especially when comparing implementations.

Output dtype matters independently. A derivative can be negative or larger than 255; retaining uint8 output can clip those values. For an 8-bit grayscale input, cv2.Sobel(gray, cv2.CV_32F, 1, 0, ksize=3, borderType=cv2.BORDER_REFLECT_101) preserves signed floating-point responses.

Keep analytical output separate from display conversion. Taking absolute values or rescaling for visualization destroys sign or absolute scale. Validate with constant images, ramps, and impulses, checking the interior and border separately. Specify kernel orientation and anchor as well as dtype when exact parity matters.

46. How does cross-correlation differ from mathematical convolution, and which convention do common CNN layers use?

Cross-correlation slides a kernel across an input without reversing the kernel. Mathematical convolution reverses the kernel along each spatial axis before applying the weighted sum. Ignoring boundaries, one-dimensional correlation uses sum_k w[k] * x[i + k], whereas convolution uses sum_k w[k] * x[i - k].

Common CNN layers, including PyTorch Conv2d, implement cross-correlation despite the convolution name. OpenCV filter2D also uses correlation. For a fixed asymmetric kernel, the distinction can reverse an edge response or otherwise change the output; symmetric Gaussian kernels do not expose that difference.

For learned filters, either convention can represent the same family of functions because the weights are learned. However, moving fixed filters or pretrained weights between implementations requires matching kernel orientation, anchor, padding, stride, and channel conventions. Naming alone does not establish numerical equivalence.

47. How would you match local image descriptors and reject unreliable matches before estimating geometry?

First choose a distance compatible with the descriptor: floating-point SIFT descriptors commonly use Euclidean distance, while ordinary binary ORB descriptors use Hamming distance. Do not feed binary descriptors to a matcher that interprets their bytes as meaningful continuous coordinates. Check descriptor existence and valid keypoint indices before matching.

Compare each descriptor's nearest and second-nearest candidates; a distance-ratio test rejects ambiguous alternatives. Mutual matching can further reduce inconsistent pairs, but its recall cost should be assessed. Neither filter proves that a match is geometrically correct.

Estimate a suitable geometric model with robust sampling, then inspect inlier count, spatial coverage, and reprojection error in stated coordinate units. Repeated textures may produce many mutually consistent but wrong matches. Reject degenerate point layouts and test the resulting warp on held-out correspondences or recognizable scene structure rather than accepting any returned matrix.

48. When is a homography a suitable model for aligning two images, and what can make its estimate unreliable?

A homography maps homogeneous image points using p2 ~ H * p1, with a 3-by-3 matrix defined up to scale. It is appropriate for views of a planar surface, or for ideal pinhole cameras rotating about the same optical center. With translation through a scene containing substantial depth variation, one global homography generally cannot remove parallax.

At least four nondegenerate point correspondences are needed; collinear or tightly clustered points make estimation unreliable. RANSAC can reject outliers, but a large inlier count alone does not establish the correct scene model. Specify the reprojection threshold in the coordinates actually supplied, typically pixels.

Inspect inlier coverage, residuals, conditioning, and the transformed image corners. Correct lens distortion when relevant. Repeated patterns, moving objects, rolling shutter, blur, and poor overlap can invalidate a seemingly plausible alignment. Evaluate errors away from the fitted points as well as at them.

49. How would you calibrate a fixed camera and check whether its distortion correction is useful?

Capture a calibration target with known geometry at varied orientations, distances, and positions across the image, while keeping the intended resolution, focus, zoom, and lens configuration fixed. Detect target points accurately and pair their pixel coordinates with object coordinates whose units are documented. Estimate intrinsics and the chosen lens-distortion model from these correspondences.

Inspect per-view and spatial reprojection errors, not just a single training RMS value. Large edge errors may expose inadequate target coverage or a poor lens model. Evaluate on additional target images and check whether undistorted straight structures appear straight and downstream measurements become more consistent.

Undistortion changes the image geometry and can crop or introduce empty borders; record the new camera matrix and valid region. Resizing or cropping requires corresponding intrinsic-coordinate updates. Physical changes to focus, zoom, lens attachment, or camera assembly may require recalibration rather than reusing the original parameters.

50. For rectified stereo with focal length 800 pixels, baseline 0.12 meters, and disparity 24 pixels, what depth is estimated and what assumptions matter?

For the standard rectified stereo geometry, depth along the camera's optical axis is Z = f * B / d. Substituting the values gives Z = 800 * 0.12 / 24 = 4 meters. This is optical-axis depth, not necessarily the Euclidean distance from the camera to the point.

The focal length and disparity must use the same pixel scale, and the baseline must be in the desired output length units. The simple equation assumes matching rectified principal-point coordinates, or disparity already corrected for their offset. Correspondences should refer to the same scene point in synchronized, distortion-corrected images.

Check the matcher's disparity representation: some OpenCV stereo outputs store disparity multiplied by 16 and require conversion. Reject invalid or near-zero disparities rather than reporting a huge confident depth. Occlusion, weak texture, calibration error, and disparity noise can make the estimate unreliable.

51. What is the theoretical receptive field after three 3-by-3 convolutions with stride 1 and dilation 1, and how does a stride change the calculation?

Three consecutive 3-by-3, stride-1, dilation-1 convolutions have a theoretical receptive field of 7 by 7 input pixels. Starting from one pixel, each layer adds two pixels along each axis: 1 -> 3 -> 5 -> 7.

Track both receptive-field size r and sampling jump j, the distance between neighboring features in input coordinates. Begin with r = 1 and j = 1; for each layer, use r_new = r + (k - 1) * d * j and j_new = j * s, using the old jump in the first equation.

If the first convolution has stride 2 and the others retain stride 1, the sizes become 3, 7, and 11, while the final jump is 2. Moving that stride later changes the result. Padding affects boundary coverage and alignment; the effective learned influence can be smaller than this theoretical extent.

52. How many trainable parameters are in a 3-by-3 convolution from 16 to 32 channels with groups equal to 1 and one bias per output channel?

The layer has 32 * 16 * 3 * 3 + 32 = 4,640 trainable parameters. Each of the 32 output channels has a kernel covering all 16 input channels, giving 144 weights per output channel, plus one bias.

More generally, a grouped convolution has C_out * (C_in / groups) * k_h * k_w weights, with an additional C_out parameters if bias is enabled. The input and output channel counts must satisfy the grouping constraints. For this example, the PyTorch weight shape is (32, 16, 3, 3) and the bias shape is (32,).

Image height, image width, and batch size do not change this parameter count because the same weights are reused spatially and across examples. They do change computation and activation memory. Removing the bias reduces the count to 4,608, not the number of multiply-accumulate operations.

53. How does a residual connection help optimize a deep network, and what happens when tensor shapes differ?

A residual block learns a correction to a shortcut, often written y = x + F(x). The direct path lets information and gradients bypass some learned transformations; the network need not reconstruct an identity mapping through every layer. This can make deep networks easier to optimize, although it does not guarantee good generalization or eliminate poor training choices.

Elementwise addition requires compatible shapes. With NCHW tensors, both branches normally need the same batch, channel, height, and width dimensions. If the block changes channels or spatial resolution, a learned projection, commonly a 1-by-1 convolution with an appropriate stride, can align the shortcut. Other architectures use explicitly specified padding or subsampling.

Check spatial alignment as well as dimensions: two tensors of equal size can represent differently positioned samples. Distinguish additive residual connections from encoder-decoder skip connections that concatenate features and therefore change the channel count.

54. How would you freeze and then fine-tune a pretrained backbone without unintentionally changing its preprocessing or normalization behavior?

Save the pretrained weights' preprocessing contract first: channel order, input range, resize and crop policy, and normalization statistics. Reuse it while training a replacement head; changing preprocessing unintentionally makes the transfer experiment difficult to interpret.

In PyTorch, set backbone parameters' requires_grad to False and optimize the head. This does not freeze normalization buffers. Calling the whole model's train() can still update backbone BatchNorm running statistics, so explicitly set the backbone to evaluation mode when those statistics should remain fixed, including after later mode changes.

After the head stabilizes, unfreeze selected layers and use a smaller, explicitly configured learning rate. Update the optimizer's parameter groups so newly trainable parameters are actually included. Decide whether normalization statistics should adapt, particularly with small batches, rather than changing that behavior accidentally. Select the schedule on independent validation data and keep the final test set untouched.

55. What logits and target shapes does PyTorch cross-entropy expect for multiclass classification and semantic segmentation?

For hard-label multiclass classification, cross-entropy accepts floating-point raw logits of shape (N, C) and integer class targets of shape (N,). Targets use torch.long with values from 0 through C - 1. For semantic segmentation, the corresponding shapes are (N, C, H, W) and (N, H, W).

Python example (PyTorch)

import torch.nn.functional as F

# logits: floating point [N, C, H, W]
# labels: torch.long [N, H, W]; 255 marks ignored pixels
loss = F.cross_entropy(logits, labels, ignore_index=255)
import torch.nn.functional as F

# logits: floating point [N, C, H, W]
# labels: torch.long [N, H, W]; 255 marks ignored pixels
loss = F.cross_entropy(logits, labels, ignore_index=255)
import torch.nn.functional as F

# logits: floating point [N, C, H, W]
# labels: torch.long [N, H, W]; 255 marks ignored pixels
loss = F.cross_entropy(logits, labels, ignore_index=255)

Do not apply softmax first: the loss handles the log-softmax calculation internally. An extra singleton channel in a hard segmentation target is not the expected shape. Probability targets are also supported, but must be floating point, match the logits' shape, and form valid class distributions. ignore_index applies to index targets. Ensure a batch has valid supervised pixels before using mean reduction.

56. When would you use binary cross-entropy with logits instead of multiclass cross-entropy for image predictions?

Use binary cross-entropy with logits when predictions represent independent binary events: one defect present or absent, several image tags that can coexist, or a binary foreground mask. Multiclass cross-entropy instead models competition among mutually exclusive classes at each supervised position.

For multilabel classification, logits and floating-point targets both have shape (N, C); targets are usually zeros and ones. For one-channel binary segmentation, both can have shape (N, 1, H, W). Unlike hard-label multiclass targets, binary targets retain the output channel dimension when the logits have one.

Pass raw logits directly to BCEWithLogitsLoss; its combined sigmoid-and-loss calculation is numerically safer than applying sigmoid separately. At inference, sigmoid yields a probability per binary event, with thresholds selected on validation data. Do not apply softmax across independent labels. If using positive-class weights, verify broadcasting and assess their effect on decision thresholds and calibration.

57. Why are model.eval() and disabling gradient recording separate steps in PyTorch inference?

model.eval() changes the behavior of modules that distinguish training from evaluation, such as dropout and BatchNorm. It does not disable automatic differentiation. Conversely, disabling gradient recording does not switch a model out of training mode, so dropout may remain active and normalization statistics may still change.

Python example (PyTorch)

import torch

model.eval()
with torch.inference_mode():
    logits = model(inputs)
import torch

model.eval()
with torch.inference_mode():
    logits = model(inputs)
import torch

model.eval()
with torch.inference_mode():
    logits = model(inputs)

The inputs still need the correct device, dtype, layout, and preprocessing. Evaluation-mode BatchNorm usually uses stored running statistics, but a layer configured with track_running_stats=False uses batch statistics even during evaluation. Consequently, batch composition can still affect predictions.

inference_mode() removes additional autograd bookkeeping and imposes restrictions on tensors subsequently used in gradient-tracked work. Use no_grad() when its less restrictive semantics are needed. Neither mechanism guarantees deterministic kernels or identical output across hardware and precision settings.

58. How would you tell whether slow training is caused by image decoding, augmentation, data transfer, or model computation?

Measure stages separately and compare them with the complete training step. Time image reading and decoding, CPU transformations, batch assembly, host-to-device transfer, forward computation, backward computation, and optimizer updates. Inspect device utilization and host worker activity together; low accelerator utilization alone does not identify the bottleneck.

A useful controlled comparison feeds already prepared tensors to the model, then restores loading and augmentation incrementally. This separates a compute limit from an input-pipeline limit without pretending that synthetic-input throughput is production throughput. Record batch size, image sizes, worker count, storage location, and caching state.

Warm up the workload and use synchronization or device events when measuring asynchronous accelerator operations. Assess overlap rather than simply summing isolated timings. Tune workers, prefetching, pinned memory, and transfer strategy according to evidence; excessive workers or caching can worsen contention or memory pressure. Recheck numerical behavior after moving or replacing transforms.

59. How would you split a dataset containing adjacent video frames and repeated views of the same physical item?

Split independent groups, not individual frames. Adjacent frames share scene content, and repeated views of the same physical item share item-specific cues. If those observations cross splits, a model can appear to generalize while mostly recognizing near-duplicates or familiar items.

Create identifiers for physical items, recording sessions, and other relevant acquisition dependencies. Where an item occurs in several recordings, preserve the connected group of related observations rather than independently grouping each recording. Use a group-aware splitter and inspect whether each split still contains useful class coverage.

Match the split to the deployment question: testing on unseen items differs from testing on future production periods or unseen cameras. Document that distinction, and reserve the final test groups before fitting normalization, selecting augmentations, or tuning thresholds. Perform duplicate checks across splits and report independent item or session counts in addition to raw image counts.

60. How would you compare class weighting, resampling, and collecting more labels for an imbalanced vision task?

Class weighting changes each example's contribution to the loss without creating new visual evidence. Resampling changes how often examples appear: oversampling can repeatedly expose the same rare items, while undersampling discards some majority-class coverage. Collecting well-targeted labels can add genuinely new rare-case variation, but costs time and requires consistent annotation.

Compare interventions using the same independent splits, model budget, and preprocessing. Keep validation and test distributions representative of deployment instead of artificially balancing them to make the score look better. Track rare-class precision and recall, false alarms, and performance across sites or object types, not accuracy alone.

Choose weights and sampling rates on validation data, and avoid accidentally multiplying their effects without intent. Repeated views of a rare item are not independent new cases. Since weighting and sampling can alter score calibration, retune operational thresholds and inspect review workload before deciding that an intervention improved the system.

61. How would you select hyperparameters and an early-stopping point without repeatedly tuning against the test set?

Reserve the test set before model selection and use training data to fit weights. Choose hyperparameters, augmentation settings, checkpoint selection, and decision thresholds with a validation set or an appropriately grouped cross-validation procedure. Fit any learned preprocessing only within each training partition.

Define the selection metric and early-stopping rule in advance, including patience and the minimum meaningful improvement. Save the best validation checkpoint rather than assuming the final epoch is best. Compare trials under a consistent budget and record unsuccessful experiments as well as successful ones.

Repeated experimentation can overfit the validation set too. For extensive searches or small datasets, nested cross-validation or an additional untouched evaluation set can provide a less biased estimate. Once the pipeline is frozen, evaluate the final test set under the declared protocol. If its results trigger redesign, treat it as development evidence and obtain fresh independent final evaluation data.

62. How do one-stage and two-stage detectors organize their predictions, and why is neither always faster or more accurate?

A two-stage detector first proposes candidate regions, then classifies and refines selected regions using region-specific features. Faster R-CNN, for example, uses a learned region proposal network and shares backbone computation. A one-stage detector predicts object classes and locations directly from image feature locations without that separate proposal-then-refinement pipeline.

This distinction does not establish a universal speed or accuracy ordering. Backbone size, input resolution, feature pyramids, proposal counts, number of predictions, training recipe, and postprocessing can outweigh the stage count. Implementations within either family differ substantially, including whether they use predefined anchors.

Compare models on the same independent dataset, annotation definitions, metric protocol, and target hardware. Measure preprocessing, inference, and postprocessing at the required batch size and concurrency. Include small-object recall, crowded scenes, memory, and tail latency rather than choosing an architecture from its family name alone.

63. How would you implement or explain greedy non-maximum suppression for scored boxes of one class?

Greedy NMS sorts one class's boxes by score, keeps the highest-scoring box, removes remaining boxes whose IoU with it exceeds a chosen threshold, and repeats. It compares candidates against kept boxes, not against every higher-scoring box indiscriminately.

Python example (PyTorch)

import torch
from torchvision.ops import nms

# Continuous pixel-edge xyxy boxes; scores correspond row-for-row.
boxes = torch.tensor([[0., 0., 10., 10.],
                      [1., 1., 11., 11.],
                      [20., 20., 30., 30.]])
scores = torch.tensor([0.9, 0.8, 0.7])
kept_indices = nms(boxes, scores, iou_threshold=0.5)
import torch
from torchvision.ops import nms

# Continuous pixel-edge xyxy boxes; scores correspond row-for-row.
boxes = torch.tensor([[0., 0., 10., 10.],
                      [1., 1., 11., 11.],
                      [20., 20., 30., 30.]])
scores = torch.tensor([0.9, 0.8, 0.7])
kept_indices = nms(boxes, scores, iou_threshold=0.5)
import torch
from torchvision.ops import nms

# Continuous pixel-edge xyxy boxes; scores correspond row-for-row.
boxes = torch.tensor([[0., 0., 10., 10.],
                      [1., 1., 11., 11.],
                      [20., 20., 30., 30.]])
scores = torch.tensor([0.9, 0.8, 0.7])
kept_indices = nms(boxes, scores, iou_threshold=0.5)

For this convention, areas use x2 - x1 and y2 - y1, without adding one. Validate finite coordinates, positive area, and aligned scores. The NMS overlap threshold is separate from a confidence cutoff and the evaluation matching threshold. Run class-aware suppression when appropriate; this function receives no class labels. Equal-score ties may resolve differently across devices, and distinct crowded objects can suppress one another.

64. How does detection average precision summarize a ranked set of predictions, and how does COCO-style AP differ from AP at IoU 0.50?

Detection AP summarizes a confidence-ranked precision-recall curve, not precision at one confidence threshold. At a specified matching IoU, predictions are matched to eligible same-class annotations in the same image. Accumulated true and false positives determine precision and recall as progressively lower-scoring predictions are included.

The interpolation protocol matters. COCO's headline detection AP averages interpolated precision over 101 recall levels, evaluated categories, and ten IoU thresholds from 0.50 through 0.95 in steps of 0.05. Its standard summary also fixes area-range and maximum-detection settings. AP at IoU 0.50 uses only the 0.50 matching threshold, so it accepts less precise localization than stricter thresholds.

Report the evaluator, category averaging, size filters, detection limits, and crowd/ignore rules. Do not compare a custom precision-recall integration with COCO AP as if they were identical. Filtering out low-confidence predictions too early can also truncate attainable recall and change AP.

65. Why can two high-overlap predictions for one ordinary ground-truth object count as one true positive and one false positive?

For an ordinary, non-ignored, non-crowd annotation, detection matching normally permits only one prediction to claim that object at a given IoU threshold. If two same-class predictions both overlap the single eligible object sufficiently, the score-ordered matcher can assign the first one as a true positive. The second has no unmatched eligible object left and becomes a duplicate false positive.

For a simplified image with one object and exactly those two predictions, the final counts are TP = 1, FP = 1, and FN = 0: precision is 0.5 and recall is 1. These endpoint values are not themselves AP.

This rule rewards finding each object once rather than emitting repeated boxes. Additional nearby annotations could change the assignment, while crowd and ignored regions have evaluator-specific exceptions. NMS may reduce duplicates before evaluation, but its overlap threshold is not the evaluator's matching threshold.

66. Why do object detectors combine classification and localization losses, and how does focal loss change the emphasis on easy examples?

A detector must answer both what an object is and where it is. Its objective therefore combines classification or objectness terms with localization terms, such as coordinate regression or overlap-based losses. Depending on the architecture, box regression applies only to matched positive examples. The matching rule, loss normalization, and relative weights affect which errors dominate training.

Focal loss modifies classification loss to reduce the contribution of already-easy examples. One form is FL = -alpha_t * (1 - p_t)**gamma * log(p_t), where p_t is the predicted probability of the correct binary outcome, alpha_t is an optional balancing factor, and gamma >= 0 controls focusing. With gamma = 0, it becomes alpha-weighted cross-entropy.

This is not simply inverse class-frequency weighting. It can help when numerous easy negatives dominate, but may emphasize incorrect hard labels too. Evaluate its effect on independent data instead of assuming it fixes every imbalance problem.

67. How can a feature pyramid help detect small and large objects in the same image?

A feature pyramid exposes representations at several spatial resolutions. Fine-resolution maps preserve more detail for small objects, while coarse maps offer broader context and can represent large objects efficiently. A Feature Pyramid Network combines a backbone's bottom-up hierarchy with top-down upsampling and lateral connections, enriching fine-resolution features with higher-level semantic information.

A detection head can then use different pyramid levels for different object scales, according to the architecture's assignment rules. This differs from repeatedly running a whole model on an image pyramid, although the two strategies can be combined.

The benefit is not automatic: a very small object may already be lost during input resizing or early downsampling. Inspect pixel-size distributions, assignment behavior, and small-object recall. Higher-resolution features also consume computation and activation memory. Compare the quality and latency effects at the actual deployment image sizes rather than treating extra pyramid levels as free improvement.

68. How do an encoder-decoder structure and skip connections support semantic segmentation?

An encoder progressively extracts contextual features, often reducing spatial resolution while expanding channel capacity. A decoder upsamples and combines these features to produce a dense prediction. For multiclass segmentation in NCHW form, a typical output is floating-point logits of shape (N, C, H, W), with one class decision per output pixel.

Skip connections transfer higher-resolution encoder information into corresponding decoder stages. Concatenating or adding those features can help recover localization cues that coarse features alone represent poorly. In a U-Net-style design, concatenation increases the decoder's input channel count; it is not the same operation as a residual addition.

Check size and coordinate alignment when cropping, padding, or upsampling, especially for odd image dimensions. Upsampling cannot recreate evidence that preprocessing destroyed. Compare predictions with masks in the same coordinate frame, preserve categorical labels during mask resizing, and inspect boundaries and small regions as well as aggregate overlap.

69. How are Dice and IoU related for the same nonempty binary masks, and what policy is needed for empty masks?

Let I be the intersection area, P the predicted foreground area, and G the ground-truth foreground area. Then IoU = I / (P + G - I) and Dice = 2 * I / (P + G). For the same binary masks with nonempty union and no smoothing, Dice = 2 * IoU / (1 + IoU). For example, IoU 0.5 corresponds to Dice about 0.667.

This illustrative function explicitly leaves the empty-empty case undefined:

Python example (NumPy)

import numpy as np

def overlap_scores(pred, truth):
    # Inputs: matching-shape boolean masks, excluding ignored pixels.
    intersection = np.count_nonzero(pred & truth)
    total = np.count_nonzero(pred) + np.count_nonzero(truth)
    if total == 0:
        return np.nan, np.nan
    return intersection / (total - intersection), 2 * intersection / total
import numpy as np

def overlap_scores(pred, truth):
    # Inputs: matching-shape boolean masks, excluding ignored pixels.
    intersection = np.count_nonzero(pred & truth)
    total = np.count_nonzero(pred) + np.count_nonzero(truth)
    if total == 0:
        return np.nan, np.nan
    return intersection / (total - intersection), 2 * intersection / total
import numpy as np

def overlap_scores(pred, truth):
    # Inputs: matching-shape boolean masks, excluding ignored pixels.
    intersection = np.count_nonzero(pred & truth)
    total = np.count_nonzero(pred) + np.count_nonzero(truth)
    if total == 0:
        return np.nan, np.nan
    return intersection / (total - intersection), 2 * intersection / total

If only one mask is empty, both scores are zero. For empty-empty masks, declare whether the evaluation excludes the case or assigns a chosen value. Report aggregation and empty-case counts; changing that policy can materially alter the mean.

70. How should ignored pixels and classes absent from an image be handled when computing segmentation metrics?

Remove ignored pixels from both prediction and target contributions before computing the confusion matrix or overlap counts. Setting their target to background is not equivalent: it can create artificial true negatives or false positives. The training loss's ignore_index does not automatically configure a separate metric implementation.

For each class, compute IoU = TP / (TP + FP + FN). If the class is absent from ground truth but predicted, its false positives produce a nonzero denominator and an IoU of zero. If it is absent from both, the denominator is zero and requires an explicit undefined-case policy.

One reproducible approach sums counts across all valid dataset pixels, computes each class's IoU, and excludes only classes with zero dataset-wide union from the macro mean. State whether background is included and report excluded classes. Averaging image-level ratios answers a different question and can heavily weight empty images; follow the chosen benchmark rather than silently mixing conventions.

71. How many non-overlapping 16-by-16 patches come from a 224-by-224 image, and what changes if the image dimensions double?

A 224-by-224 image divides into 14 patches along each axis when the patch size is 16 by 16, giving 14 * 14 = 196 patch tokens. With both image dimensions doubled to 448, there are 28 * 28 = 784 patches: four times as many tokens, not twice as many.

For dense self-attention, the pairwise attention-score matrix per head has shape (L, L). Ignoring additional tokens, quadrupling L multiplies its entry count by 16. A model using one class token instead has sequence lengths 197 and 785, so the ratio is close to, but not exactly, 16.

This does not imply that total model runtime or memory grows exactly sixteenfold: projections, feed-forward layers, kernels, and attention implementations have different costs. Higher resolution may also require positional-embedding adaptation. Keep patch size fixed in this comparison; changing it changes the token count and detail represented.

72. How would you use class, object size, lighting, and camera slices to investigate an aggregate vision score?

Break the evaluation into predefined slices that reflect plausible failure mechanisms: class, object pixel size, lighting, camera, and their useful intersections. Use the same frozen predictions and consistent metric definitions, rather than tuning a new confidence threshold for each slice after seeing test results.

Report independent image, item, or session counts alongside each score. A severe failure on a small slice can disappear in a large aggregate, but a score based on a handful of correlated frames is also unstable. Add uncertainty estimates that resample the relevant independent groups when feasible.

Inspect representative false positives, false negatives, and localization or boundary errors to distinguish annotation issues from model failures. For detection, specify how size bins and ignored objects affect scoring. Prioritize fixes using failure severity, prevalence, and coverage gaps, then verify them on fresh or reserved validation data. Slice analysis generates hypotheses; it does not by itself establish their cause.

73. How would you choose a classifier's decision threshold when missed defects and false alarms have different costs?

Select the threshold on representative validation data using explicit operational costs or constraints. If a missed defect costs C_FN and a false alarm costs C_FP, a simple empirical objective is C_FN * FN(t) + C_FP * FP(t) across candidate thresholds t. Also inspect recall, precision, and the number of items sent for review; a low-cost score may still violate a required recall floor.

For a calibrated probability of defect, constant error costs, and zero cost for correct decisions, the theoretical positive-decision threshold is C_FP / (C_FP + C_FN). This result depends on those assumptions and on probabilities reflecting deployment prevalence; it is not a universal threshold for raw model scores.

Lock the chosen rule before final test evaluation. Check its stability across cameras and operating conditions, and monitor prevalence or cost changes. If review capacity is limited, incorporate that constraint explicitly instead of silently choosing the highest F1 score.

74. What does confidence calibration measure, and why does a high confidence score not guarantee a correct prediction?

Calibration measures whether stated probabilities agree with observed frequencies. Among comparable predictions assigned about 0.8 confidence, a calibrated classifier should be correct about 80% of the time under the evaluated distribution. That is a population-level relationship, not a guarantee about any single image.

Inspect reliability diagrams and probabilistic scoring measures such as log loss or Brier score. Expected calibration error can summarize binned discrepancies, but its value depends on binning, sample size, and which confidence definition is used. Examine important classes and deployment slices instead of trusting one overall number.

Temperature scaling fits a positive scalar to logits on held-out calibration data; it can adjust confidence without changing the multiclass argmax. Assess calibration afterward on independent evaluation data. Distribution shift, unknown categories, and shortcuts can still produce confident mistakes. A high softmax score therefore cannot establish correctness, safety, or membership in the training distribution.

75. How does tracking-by-detection associate object observations across frames, and how can occlusion break that association?

Tracking-by-detection maintains temporary track states and associates each frame's object detections with those states. For example, a parcel tracker can predict a box's next position, compare candidate detections using motion and overlap, and solve an assignment problem with gates that reject implausible matches. Unmatched detections may start tracks; unmatched tracks may persist briefly before retirement.

Occlusion removes observations, increasing uncertainty in the predicted position. When similar objects cross or reappear, several assignments may be plausible, causing an ID switch or a fragmented track. Camera motion, variable frame intervals, and detector misses make the problem harder.

Record timestamps and tune the association and track-lifetime rules on representative sequences. Evaluate association errors separately from detection quality, and inspect complete occlusion-and-reappearance events. A within-sequence object track ID is an algorithmic label for continuity, not evidence of a person's real-world identity.

76. How would you benchmark end-to-end vision inference without confusing throughput, model-only latency, and user-visible latency?

Define the measured boundary first. Model-only latency measures the prepared tensor's forward computation; end-to-end latency includes decoding, preprocessing, transfer, inference, postprocessing, and any required output transfer. User-visible latency may additionally include network transport, queueing, and waiting to form a batch. Throughput is completed images or requests per second under a stated load, not simply the inverse of every latency measure.

Benchmark representative sizes and content on the target device and runtime, recording batch size, concurrency, precision, model version, and power settings. Separate cold startup from warmed steady-state measurements. Synchronize asynchronous device work or use appropriate device events for isolated timing.

Report latency percentiles, sample counts, and throughput together. Include preprocessing and NMS when they are part of the serving contract. Check memory and sustained-load behavior; a short burst with favorable caches can hide queue growth, thermal effects, or variable postprocessing cost.

77. What can post-training quantization change, and why must the quantized vision model be re-evaluated?

Post-training quantization converts an already-trained model to lower-precision representations for selected weights and, depending on the scheme, activations. It can reduce stored weight size or improve hardware efficiency, but operator support, conversions, and execution kernels determine whether actual latency improves. Lower weight storage does not imply every runtime allocation becomes equally smaller.

Static activation quantization uses representative calibration inputs to estimate numeric ranges. Use permitted training or dedicated calibration data with the real preprocessing pipeline, covering relevant operating conditions without using the final test set to tune ranges. Some quantization methods do not require that calibration step.

Re-evaluate task metrics, rare classes, confidence thresholds, and representative failure cases after conversion. Compare outputs with the floating-point baseline, and verify input/output dtype, scale, and zero-point handling when integer interfaces are used. Measure latency and memory on the intended runtime. If unacceptable degradation remains, revise calibration or consider quantization-aware training.

78. What tests would you run after exporting a vision model to a different runtime?

Start with the exported model's interface: tensor names, shapes, layouts, dtypes, supported batch sizes, and dynamic-dimension constraints. Run fixed golden inputs through the original and exported runtimes in evaluation mode. Compare raw outputs with explicit absolute and relative tolerances appropriate to the precision, then compare decoded predictions and task metrics.

Exercise supported edge cases: batch size one, unusual image dimensions, images with no objects, dense detections, and outputs near confidence or NMS thresholds. Small numeric differences can change discrete postprocessing results even when tensor-level errors appear small. Verify class order and the mapping of boxes or masks back to original image coordinates.

Test the full production preprocessing and postprocessing path, not just a hand-prepared tensor. Inspect unsupported operators, fallback execution, startup cost, latency, and memory on the target hardware. Preserve model, exporter, runtime, and preprocessing versions with the parity evidence so later changes can be compared against a stable baseline.

79. Which seeds, data artifacts, library versions, and runtime settings would you record to make an experiment reproducible?

Record the exact dataset and annotation versions, split manifests, class mapping, preprocessing recipe, augmentation configuration, and initial checkpoint. Preserve the training configuration, code revision, optimizer and schedule settings, effective batch size, and checkpoint-selection rule. For a resumed run, save optimizer, scheduler, scaler, and relevant random-number-generator states alongside model weights.

Seed each randomness source actually used: Python, NumPy generators, framework generators, data-loader workers, shuffling, and distributed samplers. Record library and driver versions, accelerator model, precision modes, deterministic-operation settings, and relevant backend configuration. A single framework seed does not control every independently constructed generator.

Reproducibility has levels: comparable metrics, numerically close outputs, and bitwise-identical execution are different goals. Deterministic settings can reduce performance or expose unsupported operations, and results may still differ across releases or hardware. Save evaluation code, predictions where appropriate, and experiment logs so another team can explain differences rather than merely rerun a seed.

80. How would you detect inconsistent bounding boxes, class mappings, or mask annotations before training?

Validate annotation structure before training: image IDs must resolve, dimensions must match decoded images, class IDs must map to the intended vocabulary, and instance fields must have aligned lengths. Check finite box coordinates, declared xyxy versus xywh format, pixel versus normalized units, positive area, and the documented policy for out-of-bounds boxes.

For masks, check spatial dimensions, allowed class or instance IDs, ignored values, and consistency with any associated boxes. Unexpected fractional mask values can reveal inappropriate interpolation. Distinguish intentional empty annotations from missing labels; an unlabeled object is not necessarily verified background.

Use stratified visual overlays, duplicate checks, class and area distributions, and cross-annotator reviews to find problems that schema checks miss. Include tiny objects, crowded images, and transformed samples. Quarantine suspect records and resolve them against written guidelines. Version corrections and audit their impact; silently clipping or relabeling everything can conceal systematic annotation defects.

Computer Vision Interview Questions and Answers for Experienced

The experienced answers weigh task performance, robustness, latency, resource use, and maintenance. They make evaluation and deployment assumptions explicit, explain what an experiment can establish, and separate measured results from claims that would require broader testing.

81. How would you decide whether a visual inspection problem needs classical image processing, classification, detection, or segmentation?

Choose the least complex method that supplies the decision the application actually needs. Stable lighting, fixed placement, and a clear intensity or shape rule may justify thresholding, morphology, and measurements. Classification answers whether an image or crop contains a defect. Detection locates separate objects or defects with boxes. Segmentation supplies pixel-level extent when area, contour, or coverage matters; instance segmentation also separates touching instances.

For example, rejecting a package because its seal is missing may need classification, while measuring the length of a narrow tear requires localization and sufficient spatial resolution. A detector followed by a classical measurement can be more practical than a single large model. Compare candidates on independent production batches, including allowable defects and nuisance variation. Account for annotation effort, missed-defect cost, false rejects, camera resolution, and target-device latency. Escalate complexity only when the simpler baseline fails a documented requirement.

82. How would you audit a surprisingly strong image-model result for duplicates, scene leakage, and preprocessing leakage?

Freeze the reported checkpoint, predictions, split manifests, and evaluation code before investigating. Search across splits using file hashes for exact duplicates and perceptual similarity for resized, recompressed, or cropped copies. Manually inspect near-duplicate candidates: similarity alone does not establish duplication. Group frames from the same video, burst, physical item, or acquisition session before splitting, and check whether site or time information indirectly reveals the label.

Trace every fitted preprocessing step. Normalization statistics, feature selection, learned imputation, augmentation policy selection, and threshold tuning must not use the held-out test set. Also examine caches, filename-derived labels, pretrained-data overlap, and repeated model selection against test results. Rebuild a genuinely independent split and fit the full pipeline again using training data only. Report both the original and corrected protocols rather than quietly replacing the score. A large drop is evidence to investigate, not proof that any single suspected leak caused it.

83. What should a dataset release record about provenance, permitted use, consent, coverage, and retention?

A dataset release should describe where the images came from, who collected them, the collection period, camera or acquisition conditions, and transformations from raw capture to the released files. Preserve stable identifiers and dataset versions so corrections and removals can be traced. Record annotation definitions, annotator instructions, quality checks, ambiguous cases, and known missing labels.

Document permissions, licenses, permitted purposes, restrictions, and any consent process without assuming that public availability authorizes every downstream use. State which populations, locations, object types, and operating conditions are represented or missing, and distinguish measured coverage from assumptions. Describe sensitive content, access controls, retention periods, deletion procedures, and responsibility for updates. Include how dependent copies and derived datasets are handled when a record must be removed. A release review should identify unresolved rights or privacy questions for the appropriate owner; documentation alone does not establish compliance or make an unsuitable use acceptable.

84. With a fixed labeling budget, how would you balance uncertain examples, diverse examples, rare cases, and a representative evaluation set?

Reserve a representative evaluation sample before using model uncertainty to choose training examples. Otherwise, the apparent improvement may reflect an evaluation set selected for the acquisition strategy rather than deployment conditions. Split by independent scene, item, or session, and keep this evaluation set outside the active-learning loop.

For training, combine several acquisition signals: uncertain predictions, diverse feature-space regions, underrepresented operating conditions, and rare but important cases. Uncertainty-only sampling can repeatedly select near-duplicate frames or unlabelable images. Diversity alone can overlook a small, consequential failure mode. Deduplicate candidate batches and consider annotation time, not just image count; one segmentation mask may cost much more than one classification label. Use a small random component to discover confidently wrong regions. After each round, compare learning curves against a random-sampling baseline at matched labeling cost. Track the sampling policy and label quality, and treat any allocation percentages as tunable choices rather than universal rules.

85. How would you judge an apparent improvement on a rare class when the evaluation set contains very few independent examples?

Start with the number of independent rare-class cases, not the number of image crops or adjacent video frames. An increase from 8 to 9 successful detections among 10 independent objects changes observed recall from 80% to 90%, but one case drives the entire difference. Report the numerator, denominator, operating threshold, and uncertainty alongside the percentage.

Compare models on the same held-out cases and inspect which outcomes changed. Use a binomial interval for a suitable independent recall estimate, or a paired cluster bootstrap over independent scenes when evaluating a more complex metric. Resampling correlated frames as independent observations understates uncertainty. With very few clusters, even bootstrap intervals are unstable and should not be presented as decisive evidence. Check annotation errors and trade-offs in false positives or other classes. The defensible conclusion may be that the improvement is promising but unconfirmed, followed by targeted collection of additional independent rare cases.

86. Two teams report different mAP for the same detector: how would you reconcile their evaluation pipelines?

First make both teams evaluate the same saved predictions against the same annotation files. If the scores still differ, the evaluator or protocol is responsible; if they agree, investigate model inference and preprocessing. Pin the evaluator implementation and version rather than comparing the label 'mAP' alone.

Check box versus mask evaluation, category-ID mappings, ignored or crowd annotations, area ranges, maximum detections, and classes without valid ground truth. COCO-style box AP normally averages IoU thresholds from 0.50 through 0.95 in 0.05 increments; AP at 0.50 is a different statistic. Confirm whether results are fractions or percentages. Then compare resizing, padding, original-image coordinate recovery, box conventions, confidence filtering, and class-aware versus class-agnostic NMS. Aggressive score filtering can truncate the precision-recall curve. Inspect per-image matches on a small hand-checked fixture, including an empty image and overlapping objects. Record numerical precision and tie handling when device-dependent differences remain.

87. A model degrades after a camera or site change: how would you separate input-pipeline defects from distribution shift?

Test the same stored raw frames through the old and new input pipelines first. Compare decoded pixels and model tensors for channel order, orientation, bit depth, numeric range, resize interpolation, aspect ratio, normalization, and crop offsets. A BGR/RGB swap or double normalization is a contract defect, not a reason to retrain immediately. Check camera metadata, firmware settings, lens changes, and calibration as well.

Once tensor parity is established, evaluate the unchanged model on labeled samples from both environments. Slice errors by lighting, object scale, viewpoint, background, exposure, and motion blur. Distribution summaries can reveal changes, but a shifted histogram alone does not prove accuracy loss. Separate acquisition changes from changes in object prevalence or labeling policy. Correct deterministic pipeline defects and retest before considering adaptation. If genuine domain shift remains, collect representative training data while preserving an independent new-site evaluation set, and verify that improvements do not damage the original deployment.

88. How would you design robustness tests for blur, low light, compression, occlusion, and unusual viewpoints without claiming universal robustness?

Build a test matrix from plausible operating conditions rather than applying arbitrary image corruption until the model fails. Include clean baselines, individually controlled blur, exposure, compression, occlusion, and viewpoint changes, plus realistic combinations. Keep the underlying scene and label paired where the transformation preserves the task. If a transformation makes the object genuinely invisible or changes the label, define that case separately.

Measure task accuracy, calibration, abstention, and latency across severity levels and relevant classes. Separate synthetic perturbations from independently collected low-light or unusual-viewpoint data: synthetic robustness is not proof of real-world robustness. Hold out corruption settings used for development and report failures, sample counts, and uncertainty rather than only an average score. Define an operating envelope and the response outside it, such as requesting a new capture. These tests support specific claims about tested conditions; they do not establish resistance to every distribution shift or adversarial manipulation.

89. How would you investigate whether a model learned a background shortcut rather than the intended visual signal?

Look for correlations between the label and background, acquisition site, watermark, packaging, or capture device. Compare performance on held-out sites and environments where those correlations change. Object-only and background-only baselines can reveal suspicious signal, although cropping can remove useful context or introduce new artifacts.

Use controlled paired tests: hold the object approximately fixed while changing the background, and vary the object while keeping the scene stable. Prefer real recaptures when possible. Synthetic background swaps require inspection because cutout edges or implausible lighting may create a different shortcut. Examine saliency or occlusion maps as diagnostic clues, not causal proof. Quantify the change in predictions and errors across many independent examples. If evidence supports a shortcut, rebalance collection, diversify contexts, or constrain the model's field of view where the task permits. Re-evaluate on untouched environments; a prettier attention map is not sufficient evidence that the shortcut disappeared.

90. How would you compare two vision architectures fairly when their training data, pretraining, image sizes, and inference budgets differ?

Separate two questions: which architecture performs better under controlled conditions, and which complete available system best meets deployment constraints. For an architecture study, match training splits, label access, pretraining data, input resolution, augmentation, optimization search effort, and evaluation protocol. Report repeated runs where practical and show uncertainty rather than selecting only the best seed.

For a deployment comparison, allow each system an appropriate configuration but impose the same operational limits, such as memory, energy, and end-to-end latency. Disclose differences in pretraining, licenses, and total development or training compute rather than attributing their benefit entirely to architecture. Measure on the actual target hardware with pinned runtime versions, precision, batch size, warm-up, and realistic input sizes. Include preprocessing and postprocessing if they are part of the service. Present an accuracy-cost trade-off curve when no candidate dominates. Parameter counts or multiply-add estimates alone cannot establish which model will be faster in production.

91. What would a production image pipeline validate and monitor before passing data to a model?

Define a versioned input contract before inference. Validate successful decoding, permitted dimensions and file sizes, channel count and order, orientation, dtype, finite values, and the expected numeric range. Treat empty, truncated, oversized, or unsupported inputs explicitly rather than silently producing a plausible tensor. For example, a model may require RGB float32 tensors shaped N,C,H,W, scaled to 0–1 and then normalized with training-time channel statistics.

Monitor capture timestamps, stale or duplicated frames, decode failures, dropped frames, exposure saturation, blur indicators, and unexpected resolution changes. Preserve the transformation needed to map boxes or masks back to original image coordinates. Maintain a small approved fixture set with expected tensor properties to detect deployment regressions. Quality thresholds should be validated against the task: a naturally dark object is not automatically a bad image. Log compact diagnostics and model/preprocessor versions, and use a defined rejection or fallback path for contract violations.

92. How would you allocate a 100-millisecond end-to-end budget across capture, preprocessing, inference, postprocessing, and communication?

Specify when the clock starts and ends: exposure start to a usable decision is different from tensor submission to model output. A provisional 100-millisecond budget might allocate 20 milliseconds to capture and decode, 10 to preprocessing, 40 to inference, 10 to postprocessing, 10 to communication, and 10 to reserve. Those are planning allowances, not measured performance or universal recommendations.

Instrument timestamps across the actual pipeline and measure tail latency under expected frame rates, concurrency, thermal conditions, and network variability. Include queueing, device transfers, cold starts, and any batching delay. Accelerator timing must account for asynchronous execution. Optimize the measured bottleneck, then retest task quality if resolution, precision, or model size changes. Overlapping stages can improve throughput without reducing the age of an individual frame. Bound queues and define stale-frame handling. Confirm the end-to-end deadline directly: adding separately measured stage percentiles does not generally produce the corresponding end-to-end percentile.

93. How would you roll out a new vision model using representative shadow or canary evaluation and a reversible versioned deployment?

Package the model with its preprocessing, postprocessing, label mapping, thresholds, runtime dependencies, and an immutable version identifier. First verify numerical and task-level parity between the reference model and exported runtime on representative inputs, including unusual shapes and edge cases. Passing export is not evidence that deployed predictions remain correct.

In shadow mode, process production-like traffic without allowing the candidate to control user-facing decisions. Compare latency, failures, and subsequently labeled outcomes across sites and operating conditions; agreement with the old model alone is not accuracy. A canary then exposes a limited, representative portion of authorized traffic to the candidate under explicit acceptance and rollback criteria. Monitor delayed labels and review workload as well as immediate service health. Keep the previous complete bundle available, test the rollback mechanism, and assign an owner. Expand only when the agreed evidence is sufficient, preserving records of which version produced each decision.

94. When would you prefer quantization-aware training over post-training quantization, and how would you choose representative calibration data?

Try post-training quantization first when a trained model and supported deployment backend are available: it is usually the simpler experiment. Compare the converted floating-point model before diagnosing quantization, so export errors are not mistaken for precision loss. Prefer quantization-aware training when post-training quantization causes unacceptable task degradation and retraining resources plus a supported quantized operator path are available.

For static integer quantization, choose calibration inputs that cover expected cameras, illumination, object scales, and preprocessing ranges, including meaningful extremes. Use the exact inference input contract and keep calibration separate from the final test set. Labels are generally unnecessary for activation-range calibration. More images do not compensate for a systematically unrepresentative sample. Quantization-aware training simulates inference quantization during optimization; it does not guarantee that the final runtime matches the simulation. Validate per-class accuracy, saturation, fallback operators, memory, and latency on the intended hardware, with converter and runtime versions recorded.

95. What numerical problems can mixed-precision vision training introduce, and how would you diagnose them?

Mixed precision can introduce float16 overflow, gradient underflow, and rounding errors in reductions or numerically sensitive operations. Bfloat16 has a wider exponent range than float16 but less mantissa precision than float32, so it is not a universal cure. Automatic mixed precision selects dtypes by operation; manually casting the entire model and every input is a different and often less stable strategy.

Compare a small reproducible run with float32, checking input ranges, loss components, gradients, and the first operation producing non-finite values. Use stable loss implementations on logits rather than manually computing probabilities and logarithms. With float16 training, gradient scaling can protect small gradients; unscale before gradient clipping or inspecting gradient magnitudes. Persistent skipped optimizer steps or a collapsing scale deserve investigation, not concealment. Run sensitive operations in float32 when justified. Record hardware support, autocast settings, scaler behavior, and framework version, then verify convergence and validation quality rather than only training speed.

96. How would you reduce training memory use while checking the effects on convergence and experiment comparability?

Profile peak memory first to distinguish parameters, optimizer state, activations, temporary workspaces, and retained computation graphs. Remove accidental graph retention in metric logging before changing the experiment. Mixed precision can reduce some storage; activation checkpointing trades recomputation for saved activations. Smaller crops, lower resolution, smaller microbatches, or a lighter model may help, but they can also change what the model learns.

Gradient accumulation can preserve the number of samples per optimizer update, but it does not reproduce large-batch batch-normalization statistics or automatically preserve loss weighting. Revisit learning-rate schedules, optimizer-step counts, and valid-pixel normalization when changing batch structure. Freezing layers or using a different optimizer changes the training problem and should be disclosed. Measure both peak allocated and reserved memory with a consistent runtime, and include throughput. Compare validation curves at matched data exposure and, where relevant, matched compute budgets. Record randomness settings and do not promise bitwise equivalence across devices or library releases.

97. How do depthwise separable convolutions reduce arithmetic compared with a standard convolution, and why might latency not improve proportionally?

For output height H, width W, kernel width K, input channels Cin, and output channels Cout, a dense convolution uses approximately H*W*K*K*Cin*Cout multiply-accumulates. A depthwise convolution with one filter per input channel followed by a 1-by-1 pointwise convolution uses H*W*(K*K*Cin + Cin*Cout). This excludes biases and assumes matching spatial outputs and a depth multiplier of one.

Python example

k, cin, cout = 3, 32, 64
dense_per_pixel = k * k * cin * cout
separable_per_pixel = k * k * cin + cin * cout
ratio = separable_per_pixel / dense_per_pixel
k, cin, cout = 3, 32, 64
dense_per_pixel = k * k * cin * cout
separable_per_pixel = k * k * cin + cin * cout
ratio = separable_per_pixel / dense_per_pixel
k, cin, cout = 3, 32, 64
dense_per_pixel = k * k * cin * cout
separable_per_pixel = k * k * cin + cin * cout
ratio = separable_per_pixel / dense_per_pixel

The arithmetic ratio is about 0.127, not a guaranteed 7.9-fold speedup. Depthwise kernels can be limited by memory traffic, launch overhead, or poor accelerator utilization, and the pointwise stage can dominate. Benchmark the complete block with actual tensor shapes, layout, dtype, batch size, and runtime on the target hardware. The factorized block also changes representational capacity, so evaluate task quality alongside latency.

98. How can distributed training or gradient accumulation change the effective batch and loss weighting for variable-sized image data?

With equal microbatches, the nominal effective image batch is world_size * images_per_rank * accumulation_steps. That count does not define the loss objective for variable-sized images. Averaging each image's loss weights images equally; averaging all valid pixels weights larger labeled regions more heavily. Padding and ignored pixels must not silently enter the denominator.

For an unweighted pixel-mean objective under standard DDP gradient averaging, let each rank accumulate a local sum of valid-pixel losses. Normalize each contribution by world_size / global_valid_pixel_count, where the count covers all ranks and the complete accumulation window. This compensates for DDP's averaging. Dividing every microbatch mean by the accumulation count is equivalent only when the relevant denominators match. Class weights can change those denominators further. Handle partial accumulation windows, sampler padding, and optimizer-step schedules explicitly. Skip globally all-ignored accumulation windows consistently across ranks. Ordinary BatchNorm uses each microbatch; SyncBatchNorm synchronizes across ranks within that microbatch, not across accumulation steps. Thus the nominal effective batch alone does not establish equivalent optimization.

99. How would you distinguish difficult examples from incorrect labels before choosing a noise-handling strategy?

High loss or low confidence identifies a candidate for review, not an incorrect label. Difficult lighting, rare shapes, occlusion, and genuine class ambiguity can produce the same signals. Sample suspected errors together with random controls, and have qualified annotators review the original image and annotation policy without being told to accept the model's prediction.

Separate clerical mistakes, missing objects, inconsistent boundaries, ambiguous categories, and genuinely hard but valid examples. Track disagreement and adjudication; an explicit ignore region or revised taxonomy may be better than forcing certainty. Correct verified labels with versioned provenance, then reassess a clean independent evaluation set. Reweighting, robust losses, or selective exclusion should follow the diagnosed problem and include checks that rare valid cases were not discarded. Focal loss addresses the contribution of easy versus hard examples in its original detection setting; emphasizing high-loss examples can also amplify mislabeled data. Do not treat a lower training loss as evidence of cleaner labels.

100. When could self-supervised visual pretraining be useful, and how would you evaluate it without contaminating the downstream test set?

Self-supervised pretraining is useful when many relevant unlabeled images are available but task labels are scarce, and the compute and data permissions justify learning a representation first. Contrastive methods, for example, train representations using different augmented views; whether those augmentations preserve the downstream signal is a task-specific question. Color removal may be inappropriate when color distinguishes acceptable from defective material.

Establish downstream train, validation, and test groups before building the unlabeled pretraining pool. Exclude test scenes, neighboring video frames, duplicate items, and derived crops for a clean inductive evaluation. If a protocol deliberately permits unlabeled test inputs, label it transductive and do not compare it as though the test set were unseen. Compare random initialization, available supervised pretraining, and self-supervised pretraining with matched labeled data and transparent compute budgets. Evaluate both frozen representations and fine-tuning where useful, with several label-budget levels and an untouched final test set.

101. How would you choose between a CNN and a vision transformer for a data-limited deployment with a fixed compute budget?

Start with deployable pretrained candidates rather than assuming that the architecture family determines the answer. A compact CNN offers useful local structure and weight sharing, and may be a strong baseline with limited labeled data. A pretrained vision transformer can transfer well, but its value depends on pretraining coverage, adaptation strategy, and the target task. Results from large-data pretraining do not establish superiority when training from scratch on a small dataset.

Compare frozen-feature and fine-tuned variants using the same independent splits and a bounded tuning budget. Measure memory, batch-one latency, power where relevant, and accuracy on the actual accelerator and runtime. For a conventional global-attention ViT, increasing resolution increases patch count and attention work substantially; patch size can also obscure small defects. CNN downsampling can lose those details too. Include pretrained-data permissions and model-maintenance costs. Choose the candidate meeting the error and resource constraints, not the one with the newest architecture label.

102. What does a CLIP-style model make possible for text-guided image classification, and what must be tested before relying on zero-shot predictions?

A CLIP-style model places images and text descriptions in a shared embedding space. Classification can compare an image embedding with embeddings of candidate class descriptions and rank their similarity, without training a task-specific classifier on labeled examples. The descriptions and candidate set are part of the classifier: changing 'a damaged carton' to a different phrase, or adding a competing class, can change predictions.

Validate prompt variants on development data, then freeze them before testing. Include difficult neighboring categories, absent classes, domain-specific terminology, and images unlike the pretraining distribution. Test per-class performance, score calibration, rejection behavior, and sensitivity to irrelevant text or background cues. Similarity-derived softmax scores are relative to the candidate set, not guaranteed probabilities that the world contains only those options. Compare against a simple supervised baseline at the available label budget. Record checkpoint, preprocessing, tokenizer, prompts, and embedding normalization; zero-shot capability does not establish suitability for every new visual task.

103. How would you evaluate a promptable segmentation model for a domain where prompts and mask quality vary?

Treat the prompt policy as part of the system being evaluated. A segmentation model given a precise ground-truth box has an easier problem than one given a rough user click, so report those protocols separately. Define whether prompts are points, boxes, or masks, how they are generated, and whether additional corrections are allowed. Keep object instances and scenes independent across development and evaluation.

Measure mask IoU or Dice together with boundary quality, failure rate, and the number of interactions or seconds needed to reach an acceptable result. Test ambiguous prompts, nearby objects, small or thin structures, and variation in annotator behavior. If the model offers several masks, evaluate the actual selection rule rather than retrospectively choosing the best mask using ground truth. Report prompt perturbation sensitivity and confidence calibration where applicable. A plausible mask does not automatically supply the intended semantic label. Validate the named checkpoint and domain instead of transferring broad foundation-model claims into deployment guarantees.

104. How does DETR's set prediction and bipartite matching differ from a detector that relies on duplicate removal with NMS?

Original DETR predicts a fixed set of object-query outputs, each containing a class distribution and a box. During training, bipartite matching assigns ground-truth objects one-to-one to predictions using a cost that combines class and box agreement. Matched outputs receive object losses; unmatched outputs are trained toward a no-object class. This set-based objective is permutation-invariant with respect to output order and discourages duplicate predictions.

A conventional dense detector can produce several high-scoring boxes for one object, then use NMS at inference to remove overlapping lower-scoring candidates. DETR's original design does not require that duplicate-removal step; matching is a training assignment mechanism, not inference-time NMS with another name. The query count bounds the number of output objects, and optimization, small-object behavior, memory, and training schedule still matter. Removing NMS does not guarantee zero duplicates or superior speed. Distinguish the original formulation from later detector variants rather than assuming every transformer detector uses the same assignment and postprocessing.

105. What changes when a detector predicts boxes without predefined anchors, and what design choices still remain?

An anchor-free detector does not regress every prediction from a predefined collection of box shapes and aspect ratios. For example, FCOS predicts at feature-map locations and regresses distances to an object's left, top, right, and bottom boundaries. This removes anchor-shape selection, but it does not remove the need to decide which locations supervise which objects.

Design choices remain around feature-pyramid levels, scale ranges, center sampling, ambiguous overlapping targets, classification and regression losses, and quality scoring. Other anchor-free designs may use centers, corners, or different assignments, so the term alone is not a complete architecture specification. Coordinate units must be clear: distances may relate to input-image pixels or feature-map stride. Anchor-free also does not mean NMS-free; FCOS uses suppression to handle duplicate candidates. Compare recall for small and crowded objects, annotation sensitivity, and end-to-end latency under a matched protocol instead of attributing every difference to the presence or absence of anchors.

106. Why can ordinary NMS miss neighboring objects in crowded scenes, and how would you compare suppression alternatives?

Greedy NMS assumes that a lower-scoring box with sufficiently high IoU against a selected box is redundant. In a crowded scene, the boxes of two distinct neighboring objects can overlap enough to trigger suppression. Raising the overlap threshold may recover the second object but can also retain more duplicates.

Compare alternatives using identical pre-suppression predictions so the effect of postprocessing is isolated. Soft-NMS reduces scores as a function of overlap rather than immediately deleting every overlapping candidate, although subsequent score thresholds can still remove them. Keep class handling, score filtering, maximum detections, and evaluator crowd rules explicit. Tune only on development scenes and assess ordinary as well as crowded scenes. Report AP, recall at useful false-positive rates, duplicate detections, and latency on the target device. Inspect paired examples to distinguish suppression errors from missing raw detections: no suppression method can recover an object for which the detector produced no adequate candidate.

107. How would you evaluate segmentation of thin structures when good global overlap hides poor boundary quality?

Report thin structures separately from large filled regions and background. Global pixel accuracy can be dominated by background, while aggregated overlap can hide missing narrow branches or small gaps. Evaluate per-class and per-instance IoU or Dice under an explicit empty-mask and ignore-region policy, then add a boundary-sensitive measure such as Boundary IoU or boundary precision and recall.

Specify how boundaries are extracted and the matching tolerance, in pixels or physical units when calibration supports it. A two-pixel error has different meaning at different resolutions. If continuity matters, also measure broken components, missing connections, or task-specific path completeness; boundary agreement alone does not prove correct topology. Use representative high-resolution annotations and inspect disagreements because the true contour may itself be uncertain. Keep resizing, interpolation, and mask thresholds fixed across models. Validate any boundary-focused training change on the original overlap metrics too, so an apparent improvement is not merely thicker predicted structures.

108. How would you choose between a homography, a fundamental matrix, and an essential matrix for two-view geometry?

Use a homography for correspondences on a common plane, or for an ideal perspective camera undergoing pure rotation after distortion is handled. It maps homogeneous image points as p2 ~ H @ p1. It is not a valid global warp for a general three-dimensional scene with translation and depth-dependent parallax.

For two perspective views of a static scene with translation, a fundamental matrix expresses the pixel-coordinate epipolar constraint p2.T @ F @ p1 = 0 without requiring known intrinsics. With calibrated cameras, an essential matrix uses normalized camera coordinates and constrains relative rotation and translation direction, not absolute translation scale. Choose robust estimation thresholds in the correct coordinate units and inspect inlier geometry, not only the count. Planarity, pure rotation, low parallax, moving objects, or concentrated matches can make pose estimation degenerate or unstable. Validate residuals and recovered geometry on held-out matches, and avoid selecting a more general model merely because it fits noisy training correspondences better.

109. Why does stereo depth become sensitive to disparity error at long range, and how would you propagate a small disparity uncertainty?

For rectified stereo with aligned principal points, focal length f and positive disparity d in pixels, and baseline B in meters, depth is Z = f*B/d. Assuming fixed calibration and small disparity standard deviation sigma_d, first-order propagation gives sigma_Z = abs(f*B/d**2)*sigma_d. At longer range disparity shrinks, so the same pixel uncertainty produces much larger depth uncertainty.

Python example

f_px, baseline_m = 800.0, 0.12
sigma_d_px = 0.25
for disparity_px in (16.0, 4.0):
    depth_m = f_px * baseline_m / disparity_px
    sigma_depth_m = f_px * baseline_m * sigma_d_px / disparity_px**2
    print(depth_m, sigma_depth_m)
f_px, baseline_m = 800.0, 0.12
sigma_d_px = 0.25
for disparity_px in (16.0, 4.0):
    depth_m = f_px * baseline_m / disparity_px
    sigma_depth_m = f_px * baseline_m * sigma_d_px / disparity_px**2
    print(depth_m, sigma_depth_m)
f_px, baseline_m = 800.0, 0.12
sigma_d_px = 0.25
for disparity_px in (16.0, 4.0):
    depth_m = f_px * baseline_m / disparity_px
    sigma_depth_m = f_px * baseline_m * sigma_d_px / disparity_px**2
    print(depth_m, sigma_depth_m)

These inputs give depths of 6 and 24 meters, with approximate uncertainties of 0.094 and 1.5 meters. This excludes calibration uncertainty, mismatches, occlusion, and correlated errors. Near zero disparity the linear approximation is unreliable. Reject invalid matches and account for implementation-specific disparity scaling before applying the equation.

110. Which camera or image-pipeline changes require revisiting calibration, and how would you validate the updated geometry?

Revisit calibration after changing the lens, zoom, focus setting, sensor mode, resolution, or image crop, and after mechanical movement changes a camera's pose or stereo baseline. Distinguish physical changes from known digital transformations. A simple resize and crop may permit an analytic update of the intrinsic matrix, whereas a lens replacement generally needs fresh calibration. Exposure or white-balance changes do not ordinarily alter ideal geometry, but can affect feature localization and practical validation.

Record the precise camera, lens settings, distortion model, resolution, coordinate convention, and image-processing chain associated with each calibration. Collect calibration views spanning the usable field of view, orientations, and relevant distances rather than many nearly identical views. Validate held-out reprojection error and its spatial pattern; a small average can hide poor image corners. For stereo, also check rectified epipolar alignment and depth against independent known distances. Recheck timing and rolling-shutter effects when moving scenes show errors that a static calibration target misses.

111. How would you compare trackers when one detects more objects but causes more association errors?

Evaluate detection and association separately before choosing an overall winner. A tracker that finds more objects may still fragment trajectories or switch track IDs, making it worse for counting completed object paths. Use identical sequences, annotation conventions, ignored regions, and frame rates, and state whether trackers share detections or use their own detectors.

HOTA provides detection and association components and combines them at each localization threshold before averaging across thresholds. Inspect those components alongside identity switches, fragmentation, missed detections, false positives, and a trajectory-oriented measure such as IDF1 where useful. Within-sequence object IDs here do not imply real-world identity recognition. Compare operating thresholds and report application outcomes, such as duplicate counts or missed conveyor-item journeys, plus latency and recovery after occlusion. Bootstrap or summarize by independent sequence rather than individual frames. A single leaderboard score cannot determine the acceptable trade-off when the application's costs of missed objects and broken associations differ.

112. How would you reduce video-processing cost by sampling frames or tracking between detections without overlooking temporal failure modes?

Choose the detection interval from the shortest important event and fastest plausible object motion, not just average frame-to-frame similarity. Detecting every fifth frame of a 30-frame-per-second stream provides only six detection opportunities per second; a short-lived object could appear and disappear between them. Tracking between detections may propagate locations cheaply, but cannot reliably discover every newly entering object or correct every drift.

Evaluate full sequences containing rapid entry and exit, occlusion, motion blur, camera motion, and dropped or irregular frames. Measure event recall, time to first detection, trajectory fragmentation, localization drift, and stale-result age as well as average throughput. Use timestamps rather than assuming uniform frame spacing. An adaptive policy can trigger detection on scene changes or low tracking confidence, but those triggers need their own validation. Benchmark decode, tracking, and detection together on the intended device. Define a maximum unchecked interval and a recovery path instead of treating reduced frame sampling as a free optimization.

113. What calibration, coordinate-frame, and timing problems arise when combining camera images with depth or other sensors?

Multi-sensor fusion requires agreement about geometry, time, and measurement meaning. Record camera intrinsics and distortion, sensor-to-camera extrinsics, axis directions, handedness, and length units. State whether an extrinsic matrix maps points into the camera frame or out of it. A depth sensor may report axial depth or radial range; treating one as the other creates errors away from the optical axis.

For projection, transform the measurement into the camera frame, reject points behind the camera, then apply the appropriate intrinsic and distortion model. Cropping, resizing, and rectification must use compatible coordinates. Align acquisition timestamps, not just packet-arrival times, and account for clock offsets, exposure intervals, rolling shutter, and sensor motion during a scan. Nearest timestamps may still mismatch a moving object. Validate overlay residuals on static and moving scenes at several distances, and propagate measurement uncertainty. Handle occlusion, missing depth, and stale measurements explicitly rather than forcing every sensor observation into a fused prediction.

114. How would you evaluate unknown or out-of-distribution inputs rather than assuming a classifier's highest softmax score detects them?

Define the intended known classes and operating domain, then build evaluation sets containing plausible unknown objects, acquisition failures, and domain shifts. Distinguish semantic novelty from degraded but still in-domain images. A classifier must distribute softmax probability over its supplied classes, so an unfamiliar input can still receive a high maximum score.

Use maximum softmax probability as a baseline, not a guarantee. Compare any alternative rejection score on development unknowns, then test on separate unknown categories or conditions to avoid tuning to a small familiar rejection set. Report both known-class performance and unknown rejection, including false rejections at a stated unknown-detection target, AUROC or precision-recall summaries, and deployment-relevant prevalence assumptions. Calibration on known validation data does not by itself solve unknown detection. Inspect confidently accepted failures and test the downstream abstention path. State which unknown families were tested; no finite collection demonstrates reliable rejection of everything outside the training distribution.

115. How would you diagnose an OCR pipeline whose text recognition fails on skewed, low-resolution, or complex-layout images?

Separate text localization, geometric correction, layout analysis, recognition, and reading-order reconstruction before changing the recognizer. Compare recognition on trusted text crops with recognition on automatically detected crops. If trusted crops work, the main defect may be layout or localization rather than language modeling.

Inspect actual character height, blur, compression, contrast, skew, perspective distortion, borders, and transparency. Enlarging a low-resolution crop can help an engine's expected scale, but it cannot recover information absent from the capture. Test deskewing, rectification, and binarization independently on a held-out document set; aggressive thresholding or morphology can erase punctuation and thin strokes. For Tesseract, record the engine version, language data, and page-segmentation mode, choosing a mode appropriate to a page, block, line, or isolated text region. Measure character and word error rates plus reading-order and field-level correctness. Review failures by document type, and prevent sensitive text or full pages from entering unrestricted debug logs.

116. How would you collect useful production diagnostics while minimizing retained images and sensitive visual information?

Begin with the question each diagnostic must answer, then collect the least sensitive signal that can answer it. Many issues can be investigated with model and preprocessing versions, input dimensions, camera configuration identifiers, timestamps at suitable granularity, failure codes, latency, and aggregate score or quality distributions. Avoid retaining full images by default merely because storage is inexpensive.

When visual samples are necessary, use an approved, limited sampling policy, access controls, encryption, short retention, and auditable deletion. Crop or redact irrelevant regions before transfer where feasible, while recognizing that redaction can fail. Blurred images, embeddings, and detailed metadata are not automatically anonymous and may still expose sensitive information. Keep diagnostic identifiers separate from unnecessary account or location details. Document who can approve exceptional capture and how samples may be reused. Evaluate whether minimization harms debugging, but resolve that trade-off explicitly rather than quietly expanding collection. Observability controls reduce risk; they do not establish universal privacy or legal compliance.

117. How would you define an authorized defensive evaluation of a vision system's failure modes without treating one benchmark as a security guarantee?

Define written authorization, the assets and interfaces in scope, the test environment, permitted data, safety constraints, and stop conditions before testing. Describe the threat or failure model: common environmental corruption, malformed inputs, resource exhaustion, model misuse, and deliberate manipulation are different evaluation categories. Use synthetic or approved data and isolated systems when a test could disrupt service or expose sensitive content.

Build reproducible cases tied to operational consequences, including input rejection, monitoring, abstention, and recovery, not only prediction accuracy. Measure failures across severity and relevant deployment conditions, with the model, runtime, and configuration recorded. A common-corruption benchmark evaluates its specified perturbations; it does not establish adversarial security, and success on a laboratory attack set is not comprehensive assurance. Track findings with owners, mitigations, and regression tests, then retest changed components. Report the tested scope and residual limitations, and do not expand into third-party systems or unauthorized data collection because the initial results look incomplete.

118. How would you design abstention and human review for uncertain predictions, including the operational cost of review?

Define the actions available to the system: accept a prediction, request a better image, route to review, or decline the task. Select thresholds on representative validation data against the costs of errors, abstention, delay, and review, then measure risk versus coverage on an independent set. Confidence calibration is useful evidence about groups of predictions, not certainty about an individual case.

Plan capacity explicitly. At 10,000 images per day, a 5% referral rate creates 500 reviews; at 30 seconds each, that is about 4.2 reviewer-hours before overhead or rework. Include bursts, queue deadlines, and what happens when reviewers are unavailable. Evaluate reviewer accuracy, disagreement, automation bias, and the interface's ability to show relevant evidence. Sample accepted predictions for audit as well, because reviewing only low-confidence cases misses confidently wrong outputs. Treat reviewed labels as a governed data source, and monitor whether domain shifts increase both error rates and review demand.

119. What can a saliency map suggest about a vision model, and why is it not proof of a faithful or causal explanation?

A saliency map can suggest which image regions a particular explanation method associates with a chosen model output. It can reveal hypotheses such as attention to a border, background texture, or watermark. Its appearance depends on the method, target score, preprocessing, and visualization normalization; a visually convincing heatmap is not proof that the model used the intended reasoning.

Apply sanity checks such as randomizing model parameters or retraining on randomized labels and testing whether the explanation changes meaningfully. Compare multiple methods and perform controlled occlusion or perturbation tests, while recognizing that the intervention may create out-of-distribution images. Measure prediction changes quantitatively rather than selecting only attractive examples. A highlighted region may correlate with the output without being sufficient, necessary, or causal in the real task. Conversely, a coarse map can miss relevant fine detail. Use explanations alongside independent performance slices, counterfactual experiments, and data audits, not as a substitute for validating model behavior.

120. What evidence should accompany a deployed vision model so another team can reproduce results, diagnose failures, and decide when to retrain or roll back?

Provide a versioned handoff bundle containing the checkpoint and integrity hash, architecture and configuration, preprocessing and output contracts, label definitions, thresholds, dependencies, and deployment hardware/runtime settings. Include dataset versions, provenance, permitted uses, split manifests, annotation policy, training configuration, seed handling, and the exact evaluation implementation. Supply approved test fixtures and expected outputs with numerical tolerances rather than promising bitwise agreement across platforms.

Report intended use, excluded conditions, per-class and relevant slice results, independent sample counts, uncertainty, latency distributions, and known failure modes. Distinguish offline accuracy from measured production outcomes. Document monitoring signals, delayed-label collection, incident ownership, and the procedure for reproducing a failed decision without unnecessary image retention. Define retraining triggers that require evidence, such as verified performance degradation or new coverage needs, not every fluctuating input statistic. Include release acceptance criteria, rollback instructions, the previous recoverable bundle, and a record of which changes require renewed validation.

Computer Vision Documentation and Further Reading

Python examples use the stated NumPy, OpenCV, or PyTorch context; API availability and behavior depend on compatible installed versions. Check image color order, value range, array or tensor layout, data type, device, and coordinate conventions before adapting a snippet. Equations and metrics use the definitions given in each answer; results from different datasets or evaluation protocols are not automatically comparable. Source review, syntax checks, and small numerical fixtures do not establish trained-model quality, deployment latency, or hardware performance. Validate those properties with representative data and the intended runtime rather than assuming a universally best model.

Use these curated references to verify image-processing and geometry methods, array and tensor behavior, model APIs, training assumptions, and evaluation protocols. Match library documentation to installed versions, and check the original method or benchmark definition when reproducing a metric or comparing results.

Team Sherlock.sh

Building fraud intelligence for live high-stake video interactions (financial discussions, hiring interviews, board meeting etc).

Catch candidate fraud before it costs you.

Sherlock AI helps you detect AI-assisted, proxy, and deepfake candidates, so every hiring decision is backed by evidence.

Ask AI about Sherlock.sh

Similar Posts