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.

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 matrix. A Mat is a small header that holds the image's size, the type of its numbers, and a pointer to one long block of pixel bytes.
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 standard library for arrays 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.

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.
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 server 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 neural network gets involved, a large part of real computer vision work is one sequence of steps, run with different settings.
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 pixel 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.
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.
| Kernel | Effect |
|---|---|
| All equal, adding up to 1 | Box blur. Every pixel becomes the average of its neighbourhood |
| Bell shaped, adding up to 1 | Gaussian blur. Also an average, but nearer pixels count more, so there are no square marks |
| Negative ring, large positive centre | Sharpen. Makes each pixel differ more from its neighbours |
| Negative left column, positive right column | Sobel. 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.
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.
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.
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.
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.
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.
Choosing between classic methods and a neural network mostly comes down to one question: can you describe what you are looking for exactly?
| Situation | Reach for |
|---|---|
| Controlled lighting, known shapes, fixed camera | Classical: threshold, contours, morphology |
| Measuring geometry, alignment, calibration | Classical: features, homographies, stereo |
| Is this a dog or a muffin, in a messy real world scene | A trained model through the DNN module |
| Needs to run at 60fps on a Raspberry Pi | Classical first, always, then a small model if that fails |
| You have 20 labelled examples | Classical, 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
imreadreturnsNonewhen 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.imshowneedswaitKey. 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 intoimg. - 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.
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 savedReferences & Primary Sources
Official specifications, standards, and documentation cited in this post.
- [1]
Primary reference manual covering Mat data structures, image filtering, geometric transformations, and feature detectors.
DOCSdocs.opencv.org - [2]
Official Apache 2.0 source code repository, architecture design specs, and algorithmic implementations.
SPECgithub.com
- Written
- Aug 22, 2026
- Length
- 2,661 words · 12 min
- Built
- …
- Served by
- …
- Delivered
- …
- Over the wire
- …
- Go's share
- …
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.
Delta, Foo, and i: The Tiny Names Hiding Inside Your Code
delta, epsilon, i and j, tmp, buf, ctx, foo and bar, nil, 0xDEADBEEF: the short words that appear in variable names rather than in meetings, and what each one actually stands for.
AI 101: It's All Just Curve Fitting
Modern AI is one idea done at a huge scale: guess a function, measure how wrong it is, adjust it to be less wrong, and repeat. Neural networks, gradient descent, embeddings and transformers: the main ideas in one post.
From C++ to Go: Demystifying Pointers, Slices, and Errors
Go code looks like C++, but the ideas behind it are different. Three things I had to learn again while building a todo app in Go: errors are values, a slice is a small header that points at the data, and the asterisk does two jobs.
Projects built with what this post is about.
