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 ⇒ levels (0–255). Distinct RGB triples:
OpenCV often stores channels as BGR order when reading files — channel index is blue, green, red in calcHist examples.
Histograms for ripeness
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.
Takeaway
| Tool | Use |
|---|---|
| RGB histogram | Color / ripeness signatures |
| Channel order | Remember BGR vs RGB |
| Frame differencing / MOG2 | Drop static background |
OpenCV / images
1 / 4Levels per RGB channel with one byte are…
Pick an answer to see if you are right.
Next: 11.9b OpenCV labs.