Skip to main content

11.9 Image processing with OpenCV

Source: Ideas from Computational Physics (Landau, Páez, Bordeianu), §11.8. Rewritten in original wording — no textbook OpenCV listing dumps. Continues 11.8b. Next: 11.9b.

Problem: separate ripe strawberries from green ones (or roast levels of coffee beans) using images.

OpenCV (opencv-python) is a computer-vision library with imaging and ML helpers. Install locally with pip install opencv-python (or the contrib build). Not available in this sandbox — labs use pure-Python histogram / difference arithmetic.

RGB pixels​

Images are grids of pixels. Each pixel stores R, G, B channel strengths. One byte per channel ⇒ 28=2562^8=256 levels (0–255). Distinct RGB triples:

256×256×256=16,777,216.256\times 256\times 256 = 16{,}777{,}216.

OpenCV often stores channels as BGR order when reading files — channel index 00 is blue, 11 green, 22 red in calcHist examples.

Histograms for ripeness​

Figures 11.12–13 — ripe vs green; RGB tone histograms.

calcHist counts how many pixels fall in each of 256 tone bins per channel. Ripe fruit tends to pile counts into red high bins; unripe fruit shifts weight toward green. Those histogram shapes become features for a classifier (or a simple threshold on red/green ratios).

# rgb_hist_sketch.py — structure (local OpenCV)
# img = cv.imread("ripe.jpg")
# for ch, color in enumerate(("b", "g", "r")):
# hist = cv.calcHist([img], [ch], None, [256], [0, 256])
# # plot hist

Background subtraction​

For video (exoplanet transits, lab pistons, smoke): keep what changes. createBackgroundSubtractorMOG2() builds a statistical background model and returns a foreground mask. Simpler pedagogy: absolute difference between consecutive frames, then threshold.

Figure 11.14 idea — static scene removed; moving parts remain.

Takeaway​

ToolUse
RGB histogramColor / ripeness signatures
Channel orderRemember BGR vs RGB
Frame differencing / MOG2Drop static background
Quiz

OpenCV / images

1 / 4

Levels per RGB channel with one byte are…

Pick an answer to see if you are right.

Next: 11.9b OpenCV labs.