OpenCV interview questions and answers for computer vision developers

OpenCV interview questions test whether you can build a working image pipeline and explain each step: reading images as arrays in BGR order, picking a color space, filtering noise, thresholding, cleaning masks with morphology, finding contours, and transforming geometry. Expect traps around coordinates, data types and color order, a short coding task on a sample image, and senior questions on feature matching, calibration, video and speed. Strong answers say why a step is needed and what breaks if lighting or scale changes.

By Published 6 min read

How OpenCV shows up in interviews

OpenCV is the default toolbox for image and video work, so it appears in interviews for computer vision, robotics, embedded, document processing, medical imaging and test automation roles. Most companies ask about the Python bindings, with C++ for performance-critical or embedded positions. The questions are practical: given an image, get a clean mask, count objects, straighten a document, or match a template. Model training, datasets and evaluation belong to computer vision engineer interview questions; this page stays on the library and the classical techniques it implements.

  1. Library basicsHow images are stored, color order, data types, reading and writing files and video.
  2. Coding taskOften on a shared screen: threshold, find contours, measure or count objects, or correct perspective.
  3. Technique questionsWhy Gaussian or median blur, why Otsu or adaptive thresholding, how Canny works, when to use morphology.
  4. Senior or system questionsFeature matching, calibration, real-time video, deploying a model with the DNN module, and speed.

OpenCV fundamentals questions

Fundamentals and common traps
QuestionWhat it testsWhat a strong answer shows
How does OpenCV store an image in Python?Data modelAs a NumPy array of shape (height, width, channels), usually uint8. Grayscale images have no channel axis.
Why do colors look wrong when you show an OpenCV image with another library?Color orderOpenCV loads color images in BGR order, while most other libraries expect RGB. Convert with cvtColor before handing the array over.
What does imread return for a missing file?Error handlingNone, not an exception. Check the result before using it, or a later call fails with a confusing error.
Pixel indexing versus drawing coordinates?CoordinatesArray indexing is [row, column], so [y, x]. Drawing functions and points take (x, y). cv2.resize takes (width, height). Mixing them is the most common bug.
What happens when you add two uint8 images?Data typescv2.add saturates at 255. NumPy addition wraps around, so 250 + 10 becomes 4. Convert to a wider type when you need exact arithmetic.
Is cropping with slicing a copy?MemoryNo, a NumPy slice is a view sharing memory with the original, so drawing on the crop changes the source. Call copy() when you need independence.
Why convert to HSV or Lab?Color spacesHue separates color from brightness, so color masks are more robust to lighting in HSV. Lab approximates perceptual differences. Grayscale throws color away, which can make some objects disappear.
Gaussian, median or bilateral blur?FilteringGaussian smooths general noise; median removes salt-and-pepper noise and keeps edges better; bilateral smooths while preserving edges but is slower.
Global, Otsu or adaptive threshold?SegmentationA fixed global threshold suits controlled lighting. Otsu picks the threshold from a two-peaked histogram. Adaptive thresholding computes a local threshold per region, which handles uneven lighting such as shadows on a document.
What do erosion and dilation do?MorphologyErosion shrinks white regions and removes small specks; dilation grows them and fills small holes. Opening (erode then dilate) removes noise; closing (dilate then erode) fills gaps.
Fundamentals and common traps. Scroll sideways on a small screen.

Segmentation and contours: a coding task

A frequent live task is to find objects in an image and report their boxes. The sample builds a synthetic image so it runs anywhere, then shows a classic trap: in grayscale, red and blue shapes lose most of their contrast against the background, while the saturation channel separates all three.

import cv2
import numpy as np

# Synthetic BGR image: three colored shapes on a noisy gray background.
img = np.full((240, 320, 3), 40, np.uint8)
cv2.circle(img, (70, 120), 40, (0, 0, 255), -1)             # red (OpenCV uses BGR order)
cv2.rectangle(img, (150, 60), (230, 180), (0, 255, 0), -1)  # green
cv2.circle(img, (280, 60), 18, (255, 0, 0), -1)             # blue
noise = np.random.default_rng(0).integers(0, 20, img.shape[:2], dtype=np.uint8)
img = cv2.add(img, cv2.merge([noise] * 3))                   # saturating add, gray noise

def count_shapes(channel):
    blur = cv2.GaussianBlur(channel, (5, 5), 0)
    _, mask = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    return [cv2.boundingRect(c) for c in contours if cv2.contourArea(c) > 100]

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
saturation = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)[:, :, 1]
print("grayscale finds", len(count_shapes(gray)))        # red and blue end up close to the background in gray
print("saturation finds", len(count_shapes(saturation)))  # every colored shape stands out
Thresholding and contours on a synthetic image. Run locally with OpenCV 4.12; output: grayscale finds 1, saturation finds 3.
  • What does findContours expect? A binary image with white objects on black. Its retrieval mode decides which contours come back (external only or the full hierarchy), and the approximation mode decides how many points describe each one.
  • How do you tell a rectangle from a circle? Approximate the contour with approxPolyDP and count vertices, or compare area to the enclosing circle or bounding box. Circularity (4π times area over perimeter squared) is near 1 for circles.
  • boundingRect or minAreaRect? boundingRect is axis-aligned. minAreaRect returns the smallest rotated rectangle, which suits tilted objects and gives the angle.
  • How does Canny edge detection work? Smooth the image, compute gradients, thin edges with non-maximum suppression, then keep strong edges and weak edges connected to strong ones using two thresholds.
  • When would you use the Hough transform? To find lines or circles from edges even when they are broken or partly hidden, such as lane lines or coins. It needs tuning for resolution and thresholds.
  • How do you measure real sizes from pixels? Calibrate the camera, use a reference object of known size in the same plane, or use a known distance, and remember that perspective changes scale across the image.

Geometry, features and calibration questions

Intermediate questions
QuestionWhat it testsWhat a strong answer shows
Which interpolation do you use for resizing?ResamplingINTER_AREA when shrinking, INTER_LINEAR or INTER_CUBIC when enlarging, and INTER_NEAREST for label masks so class values stay intact.
Affine versus perspective transform?GeometryAn affine transform keeps parallel lines parallel (rotation, scale, shear) and needs three point pairs. A perspective transform maps any quadrilateral to another and needs four, which is how you flatten a photographed document.
How do you straighten a photo of a receipt?PipelineFind the paper's outline (edges or threshold, then the largest four-point contour), order the corners, compute a perspective transform to a rectangle and warp.
ORB, SIFT or template matching?FeaturesTemplate matching suits a fixed-size, unrotated pattern. ORB is fast and binary, matched with Hamming distance. SIFT is more robust to scale and lighting and is in the main package in recent releases; older builds needed the contrib package.
What is Lowe's ratio test?Matching qualityFor each feature, compare the best and second-best match distances and keep it only if the best is clearly better. It removes ambiguous matches.
Why use RANSAC with findHomography?Robust fittingSome matches are wrong. RANSAC fits the model to random subsets and keeps the one most matches agree with, ignoring outliers.
What does camera calibration estimate?CalibrationIntrinsics (focal length, principal point) and distortion coefficients, usually from several images of a chessboard pattern. Undistorting with them makes straight lines straight again.
What are histogram equalization and CLAHE?ContrastEqualization spreads intensities over the full range. CLAHE does it per tile with a clip limit, which improves local contrast without blowing out noise.
Intermediate questions. Scroll sideways on a small screen.

Video, DNN and senior questions

Scenarios interviewers describe
ScenarioWhat to considerWhat a strong answer covers
A threshold pipeline works in the lab and fails on the factory line.LightingLighting and reflections differ. Control the lighting if possible, use adaptive thresholds or color spaces less sensitive to brightness, and test on images from the real line.
A video pipeline falls behind real time.ThroughputResize early, process a region of interest, skip frames when allowed, avoid Python loops over pixels, read frames in a separate thread, and profile each step.
You must run a trained detector without a deep learning framework installed.DNN moduleExport the model to a format the DNN module reads such as ONNX, prepare input with blobFromImage using the same scaling and channel order as training, and verify outputs against the original model.
Results differ between Python and the C++ service.ConsistencyCheck color order, data types, interpolation flags, rounding and library versions. Compare intermediate arrays step by step.
A server import fails because of missing GUI libraries.PackagingUse a headless build of the OpenCV Python package on servers and in containers, and avoid imshow there.
Should you use classical OpenCV or a learned model?JudgmentClassical methods are fast, explainable and need no labels when conditions are controlled. Learned models handle variation better but need data, monitoring and more compute. Many systems combine both.
Counting cars from a fixed camera at night.DesignBackground subtraction or a detector, plus tracking to avoid counting the same car twice, handling headlights and rain, and a line-crossing rule. Validate against hand counts.
Scenarios interviewers describe. Scroll sideways on a small screen.
  • How do you read video safely? Check that VideoCapture opened, check the return flag of each read, release the capture at the end, and do not trust the reported frame rate for timing.
  • What is background subtraction? A model of the static scene, such as a mixture of Gaussians, subtracts from each frame to leave moving objects. Lighting changes and shadows need handling.
  • Why are loops over pixels slow in Python? Each iteration runs in the interpreter. Vectorized NumPy operations and OpenCV functions run in compiled code.
  • How do you debug a vision pipeline? Save or display every intermediate image, print shapes and dtypes after each step, and build a small set of hard test images you rerun after each change.

Fictional example

Answering "Count the coins in this photo"
Interviewer
You get a photo of coins on a table, some touching. How would you count them with OpenCV?
Candidate
First grayscale and a blur to reduce texture. Then a threshold: Otsu if the table contrasts well, adaptive if lighting is uneven. A morphological opening removes specks. Touching coins will merge into one blob, so I would either use a distance transform and watershed to split them, or try HoughCircles on the blurred image with a radius range taken from the coin size. I would check the count on a few photos with different lighting and coin overlaps, and print the radius distribution to catch false circles. If the photos vary a lot in the real use case, I would say so and suggest a small trained detector instead.

OpenCV practice plan

  • Days 1 and 2: run the sample above, then change colors, noise and lighting and watch which channel and threshold still work.
  • Day 3: photograph a document at an angle and write the perspective correction pipeline end to end.
  • Day 4: match a logo in a scene with ORB, the ratio test and a homography, and draw the found outline.
  • Day 5: process a short video file: background subtraction, contours, and a frame counter. Time each step.
  • Days 6 and 7: practice explaining Canny, Otsu, morphology and RANSAC in under a minute each, and rehearse the coin question out loud.

OpenCV coding rounds move quickly, and candidates often forget to say why each step is there. Natively, an AI interview assistant for Mac and Windows, transcribes your mock vision rounds on your machine, so afterwards you can check whether you explained the blur before the threshold. In practice it can read a task, an image or an error message from a screenshot and suggest an approach, and with Pro or the free trial it can draw on the résumé and job description you add. Transcripts and notes are kept for review.

Questions people ask

What OpenCV questions are asked in interviews?

How images are stored as arrays, BGR order, coordinates and dtypes, color spaces, blurs and thresholds, morphology, Canny and contours, perspective transforms, feature matching with RANSAC, calibration and video processing.

Why does OpenCV use BGR instead of RGB?

It is a historical convention in the library. What matters in an interview is converting with cvtColor before passing images to libraries that expect RGB, and remembering it when you pick colors.

What OpenCV coding task should I practice?

Threshold an image, clean the mask with morphology, find contours and report boxes or counts. Then practice straightening a document with a perspective transform.

Do OpenCV interviews ask about deep learning?

Often a little: running an exported model through the DNN module and preparing input with matching scaling and channel order. Model training questions belong to computer vision engineer rounds.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP