L7 · Math, AI & visionComputer Vision 101 · part 1 of 2

OpenCV 101: Every Image Is a Grid of Numbers

A photo is a rectangle of numbers, and everything OpenCV does is arithmetic on that rectangle. Mat, BGR, convolution, thresholds, contours and perspective warps: the ideas that make the library's 2,500 functions easier to find your way around.

Takumi Yamada
· 12 min read · 2 references
opencvcomputer-visionimagespythoncppfundamentals
The OpenCV logo: three open rings, red at the top, green and blue below, above the word OpenCV.
The OpenCV logo. Its three shapes are the letters O, C and V, in red, green and blue, the same three colours that make up every pixel on a screen.Logo: Adi Shavit, public domain (trademark), via Wikimedia Commons (original). Changes: placed on a background.

We see an image as a face, a street, or a cat on a sofa. OpenCV sees a rectangle of whole numbers. Every function in the library, from a two-line blur to a face detector, is arithmetic on that rectangle.

That idea is the base of the whole subject.

An image is a matrix. Computer vision is what you do to matrices.

OpenCV started at Intel in 1999, so that research groups would stop rewriting the same basic tools, such as edge detectors, again and again. Its first test version came out in 2000, and it has been developed ever since. Today it's a free C++ library under the Apache 2.0 licence, and it can also be used from Python, Java and JavaScript. It runs in phones, factory cameras and surgical robots, and in most university courses on computer vision.

It also has about 2,500 public functions. That's why its documentation is hard to find your way around, and why tutorials are hard to adapt to your own problem. This post explains the ideas underneath the tutorials. Once you know these six ideas, it's much easier to find the function you need.

The one data structure

Everything in OpenCV is stored in a Mat, short for . A Mat is a small header that holds the image's size, the type of its numbers, and a to one long block of pixel .

img.shape = (480, 640, 3)480 rows × 640 columns × 3 channels = 921,600 bytescol 0col 1col 2row 0BGRBGRBGR…row 1BGRBGRBGR…row 2BGRBGRBGR…in memoryBGRBGRBGRBGRBGR…row 0, col 0row 0, col 1row 0, col 2
The grid is how you think about an image. The row underneath is how it sits in memory.

Three properties describe any image you will work with.

  • Its shape: how many rows and columns of pixels it has.
  • Its depth: the type of one number. Usually it's an unsigned byte, a whole number from 0 to 255.
  • Its channel count: how many numbers each pixel has. It's 1 for grayscale, 3 for colour, and 4 when there is transparency.

In Python, a Mat is a NumPy array. NumPy is Python's for of numbers. OpenCV doesn't convert the image into a NumPy array or wrap it in one. It is one. So img[100:200, 300:400] cuts out a piece, img.mean() gives the average brightness, img > 128 gives you a mask, and passing the image to PyTorch or Matplotlib costs nothing. I think half of the things called "OpenCV tricks" are really NumPy features.

In C++, cv::Mat is a header that shares its pixel buffer. Copying a Mat copies only the header, and both copies use the same pixels. If you have read about Go slices, it's the same idea, with the same result: copying is cheap, and when you want your own separate pixels, you call .clone().

The BGR trap

OpenCV stores the colours of each pixel in the order blue, green, red. Almost every other library on your computer uses red, green, blue.

A phone screen under a microscope: columns of tiny red, green and blue rectangles repeating in the same order.
A phone screen under a microscope. Each pixel is three small dots, one red, one green and one blue, and the screen sets how bright each dot is. An image holds one number for each of the three, and OpenCV keeps them in the order blue, green, red.Photo: RIT RAJARSHI, CC BY 4.0, via Wikimedia Commons (original). Changes: cropped.

The reason is history. Cameras and BMP image files around 2000 stored their bytes in that order, and OpenCV matched them. By the time everyone else settled on red, green, blue, too much code depended on OpenCV's order. So it stayed, and it still catches people. Load a photo with OpenCV, show it with another library, and the blue sky comes out orange. Convert the colours every time an image goes into or out of OpenCV.

rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

The other trap

OpenCV uses two orders for coordinates, on purpose, sometimes in the same few lines. When you index the array, the row comes first, so you write y then x. When you pass a point to a drawing or geometry function, x comes first, because points are written that way in geometry.

value = img[y, x]                          # indexing: row first
cv2.circle(img, (x, y), 5, (0, 0, 255))    # drawing: x first

Nothing warns you about this. If a drawing appears in the wrong place, or a crop cuts out the wrong area, this mix-up is almost always the cause.

x, the column01234y, the row0123img[1, 3]indexing:row first, so y then x(3, 1)drawing:x first, so x then y
The same pixel, named both ways.

Load it, look at it, save it

import cv2

img = cv2.imread("street.jpg")       # BGR uint8, or None
if img is None:
    raise SystemExit("could not read the file")

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imwrite("gray.png", gray)

cv2.imshow("gray", gray)
cv2.waitKey(0)                       # the window is drawn inside here
cv2.destroyAllWindows()

Two lines in that code cause the most common bugs in the whole library.

imread never raises an error. A missing file, a typo in the path, or an image format your copy of OpenCV can't read all give the same result: None. Your program then crashes forty lines later, inside some other function, with an error about NoneType. Check the result of imread every time.

waitKey isn't only a pause. It runs the window system's event loop, the code that handles drawing and key presses. The window that imshow creates is only drawn while waitKey is running. Without it you get a grey box or nothing, and it's easy to think the image didn't load. A usually has no screen at all, so there you install the headless version of OpenCV and save images to files instead of showing them.

The pipeline that solves a surprising number of problems

Before any gets involved, a large part of real computer vision work is one sequence of steps, run with different settings.

LOADBGR IMAGEas loaded3 channelsSIMPLIFYGRAYSCALEand a blur1 channelISOLATETHRESHOLDor edges0 or 255MEASURECONTOURSboxes, arealists of points
Each stage hands on less than it was given.

Counting cells on a microscope slide, reading a dial, finding the page in a photo of a page, checking that a part on a conveyor belt is the right size: all of these use the same four steps.

gray    = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur    = cv2.GaussianBlur(gray, (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)
big = [c for c in contours if cv2.contourArea(c) > 500]
print(f"{len(big)} objects")

Grayscale comes first, because colour is usually three times as much data for the same answer. Blurring comes before the threshold, because a threshold makes noise worse: one stray bright becomes one stray object. That order isn't a matter of taste. It can be the difference between finding 12 objects and finding 4,000.

Convolution: the operation under half the library

Blurring, sharpening, embossing, finding edges, and the first layer of every image model are all the same operation, with different numbers. The operation is called convolution, and it uses a small grid of numbers called a kernel.

You slide the kernel across the image, one position at a time. At each position, you multiply each kernel number by the pixel under it, add up the results, and write the total into the output image.

IMAGE PATCHKERNEL121/9151/9111/9141/9901/9131/9101/9121/9141/9×multiply, add upOUTPUT PIXEL21(12 + 15 + 11 + 14 + 90 + 13 + 10 + 12 + 14) / 9 = 21.2
A 3 by 3 box blur at one position.

The 90 in the middle was a speck of noise. Averaging it with its neighbours brought it down to 21, which matches the area around it.

Change the numbers in the kernel and you change what it does.

KernelEffect
All equal, adding up to 1Box blur. Every pixel becomes the average of its neighbourhood
Bell shaped, adding up to 1Gaussian blur. Also an average, but nearer pixels count more, so there are no square marks
Negative ring, large positive centreSharpen. Makes each pixel differ more from its neighbours
Negative left column, positive right columnSobel. Responds to vertical edges and ignores flat areas

The last row is the whole idea of edge detection. An edge is a place where the brightness changes quickly. A kernel that subtracts the left pixels from the right ones gives zero on a flat wall, and a large number exactly where the brightness jumps. Canny, the edge detector you will actually use, combines four steps: blur, measure the change with Sobel kernels, thin each edge down to one pixel, and then keep the strong edges plus any weak edges connected to them.

KERNEL-101-101-101right minus leftA FLAT WALL101010101010101010030 - 30 = 0AN EDGE101090101090101090240270 - 30 = 240
The same kernel on a flat patch and on an edge.
edges = cv2.Canny(blur, 100, 200)   # low and high hysteresis thresholds

This connects to the modern half of the field. A convolutional neural network uses this exact sliding grid. The only difference is that nobody chooses the kernel's numbers. They start random and are adjusted by training until the network's answers are good. Classic computer vision uses kernels written by hand. Deep learning uses kernels that were learned. The curve fitting post explains the learning half in the same way as this post.

From pixels to objects

A threshold turns a grayscale image into a mask, where every pixel is either 255 (white, the object) or 0 (black, the background). The basic version asks you to choose the cut-off number, and it stops working as soon as the lighting changes. Two smarter options cover most cases.

GRAYSCALE0 to 255MASK0 or 255120400200255220255900180255300240255each pixel: brighter than 128?
A threshold of 128 applied to one row of pixels.

Otsu's method chooses the number for you. It looks at how many pixels have each brightness, and picks the cut-off that splits them most cleanly into a dark group and a bright group. It works well when the lighting is even.

Adaptive thresholding chooses a different number for each small area of the image. It's the one to use for a photo of a page with a shadow across it, where no single number could work for the whole page.

Masks usually come out with small specks and holes, and morphology cleans them up. Opening shrinks shapes and then grows them back, which deletes specks smaller than the kernel. Closing grows shapes and then shrinks them back, which fills small holes inside shapes that should be solid.

OPENINGerode,then dilatethe speck is goneCLOSINGdilate,then erodethe hole is filled
Opening and closing on masks seven pixels wide. The blob itself keeps its size both times.
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8))

Then findContours follows the edge of each white shape and gives you a list of points for each one, called a contour. From a contour you can measure things that answer real questions. contourArea gives the size, boundingRect gives a box around it, minAreaRect gives a box that can be turned to fit, and approxPolyDP simplifies a jagged outline into a few straight sides. That last one is how a document scanner finds the four corners of a page.

Geometry: moving pixels around

Resizing, rotating and straightening an image are all the same idea. For each pixel of the output, work out where it came from in the input, and copy the colour from there. That mapping is written as a matrix.

An affine transform uses a 2 by 3 matrix. It can move, turn, scale and slant an image, and parallel lines stay parallel. A perspective transform uses a 3 by 3 matrix, and parallel lines don't have to stay parallel. That's exactly what you need for a photo of something flat taken at an angle.

src = np.float32([tl, tr, br, bl])                  # corners in the photo
dst = np.float32([[0,0], [W,0], [W,H], [0,H]])      # corners of the output
M   = cv2.getPerspectiveTransform(src, dst)
flat = cv2.warpPerspective(img, M, (W, H))

Four pairs of corners give one matrix, and a slanted photo of a receipt becomes a flat scan. If the idea of a matrix as something that moves points around isn't comfortable yet, Linear Algebra 101 explains it.

THE PHOTOtltrbrblone 3 by 3 matrix(0, 0)(W, 0)(W, H)(0, H)
The four point pairs from the code above. Each corner in the photo is sent to a corner of the output.

Features: how two photos of the same thing get matched

Panoramas, augmented reality and robot navigation all depend on one question: which point in this photo is the same as which point in that one?

The answer is features. A detector finds spots that stand out, such as corners. A corner still looks like a corner when the photo is turned or the light changes, while a spot on a flat wall looks like every other spot. A descriptor then sums up the small area around each spot as a short list of numbers. Matching two photos becomes a search for the closest pairs of those lists.

PHOTO APHOTO BFour matches agree on one way to move A onto B. The dotted one does not fit it and is dropped.
Feature matches between two photos. The wrong match is found because it disagrees with the rest.
orb = cv2.ORB_create(2000)
k1, d1 = orb.detectAndCompute(img1, None)
k2, d2 = orb.detectAndCompute(img2, None)

matches = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True).match(d1, d2)

Many of those matches will be wrong, so you never trust them directly. findHomography with RANSAC handles this. It picks a few matches at random, works out how one photo maps onto the other, and counts how many of the other matches agree. It does this many times and keeps the mapping that the most matches agree with. The right mapping always gets more support than any mapping built from wrong matches. ORB is the feature detector worth knowing first, because it's fast, free to use, and good enough for most jobs.

When to reach for the DNN module

OpenCV can run neural networks, but it can't train them. You train a model elsewhere, for example in PyTorch, and save it as an ONNX (Open Neural Network Exchange) file. OpenCV then prepares the image, runs the model, and draws the results.

net  = cv2.dnn.readNetFromONNX("yolo.onnx")
blob = cv2.dnn.blobFromImage(img, 1/255.0, (640, 640), swapRB=True)
net.setInput(blob)
outputs = net.forward()

blobFromImage does the preparation, and that decides whether your model is accurate or useless. It scales the pixel values to the range the model was trained on, resizes the image, swaps blue and red, and reorders the array into the layout the network expects. If one of those steps is wrong, you don't get an error. You get wrong answers that the model is very sure about.

imageH × W × 3, BGRSCALEpixel rangeRESIZEmodel's sizeBGR TO RGBchannel orderREORDERchannels firstblob1 × 3 × H × W, RGBGet one of the four wrong and there is no error. The model just gives wrong results.
What blobFromImage changes, in order.

Choosing between classic methods and a neural network mostly comes down to one question: can you describe what you are looking for exactly?

SituationReach for
Controlled lighting, known shapes, fixed cameraClassical: threshold, contours, morphology
Measuring geometry, alignment, calibrationClassical: features, homographies, stereo
Is this a dog or a muffin, in a messy real world sceneA trained model through the DNN module
Needs to run at 60fps on a Raspberry PiClassical first, always, then a small model if that fails
You have 20 labelled examplesClassical, or a pretrained model. Not training from scratch

I think going straight to a neural network is often the expensive choice. A threshold and a contour filter run in microseconds, need no training data, and can be debugged by looking at the images in between. Deep learning is what you use when the rule exists but can't be written by hand, and many factory vision problems aren't like that.

The gotchas that cost everyone an afternoon

  • imread returns None when it fails, and never raises an error. Check it.
  • BGR, not RGB. Convert whenever an image goes into or out of OpenCV.
  • Byte arithmetic wraps around. In NumPy, a byte holding 200 plus 100 gives 44, because 300 doesn't fit and the count starts again from 0. Use cv2.add, which stops at 255 instead.
  • img[y, x] for indexing, (x, y) for drawing. Two orders, and no warnings.
  • imshow needs waitKey. Without the event loop, there is no window.
  • A slice of an image isn't a copy. Writing into img[0:10, 0:10] writes into img.
  • Float images are shown on a 0 to 1 scale, byte images on 0 to 255. A float image with values up to 255 shows up pure white. It looks like a broken pipeline, but it's only how the image is displayed.
200 + 100NumPy, uint80255200300 does not fit, so it starts again from 0 and lands on 44cv2.add(200, 100)saturatesit stops at 255
The third item on the list. NumPy wraps around and cv2.add saturates.

Next Steps

pip install opencv-python          # or opencv-python-headless on a server

The official OpenCV tutorials are organized by part of the library rather than by task, so I think the best way to start is a project with a clear goal. A document scanner is a good first one. It needs grayscale, blur, Canny, contours, approxPolyDP to find four corners, and a perspective warp. That's six of this post's seven sections in about eighty lines of code. You can check every step by saving the image in between to a file.

That habit is the real skill here. Vision code doesn't crash when it's wrong. It produces output that looks reasonable but isn't. So the fastest way to find a bug is to look at the mask, instead of reasoning about it.

To sum up, OpenCV is arithmetic on images, packaged and made fast, with almost the same design it had in 2000.

Check yourself

3 questions · nothing is saved
  1. 1.You load a photo with OpenCV, show it with another library, and the blue sky comes out orange. Why?
  2. 2.cv2.imread is given a path with a typo in it. What happens?
  3. 3.Why blur an image before thresholding it?

References & Primary Sources

Official specifications, standards, and documentation cited in this post.

  1. [1]

    Primary reference manual covering Mat data structures, image filtering, geometric transformations, and feature detectors.

    DOCSdocs.opencv.org
  2. [2]

    Official Apache 2.0 source code repository, architecture design specs, and algorithmic implementations.

    SPECgithub.com

Who wrote this

Author profile and background

Takumi Yamada

Takumi Yamada

· Backend Engineer

Backend engineer building services, databases, Linux tooling, and NEGEN SYSTEMS. Writing about low-level mechanics, distributed systems, and real-world security.

End of post
NEGEN SYSTEMS
Receipt · post 29 of 31
Written
Aug 22, 2026
Length
2,661 words · 12 min
Built
…
Served by
…
Delivered
…
Over the wire
…
Go's share
…
Next in Computer Vision 101 · part 2 of 2

OpenCV 5: What Actually Changed Under the Hood

The first major version since 2018 is about foundations, not new features: a rebuilt engine that runs over 80% of ONNX instead of 22%, real n-dimensional arrays, fast code from four chip makers, and a list of removals long enough to break your build.

11 min read
From other series