Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 54 ยท Performance and Production

Common Mistakes and Debugging

Fix the classic OpenCV bugs: BGR versus RGB, imread returning None, (x, y) versus (row, column), uint8 overflow, views versus copies, even kernels and headless imshow.

OpenCV code rarely crashes loudly when it is wrong. A swapped channel gives an orange sky, a wrong coordinate order draws a rectangle in the wrong corner, and a wrapped uint8 value makes a bright pixel go dark. The program runs, the output looks "off", and you lose an hour. This lesson collects the mistakes that cause most of those hours, shows each one happening, and gives you a habit that prevents it.

The runnable examples recreate each trap with NumPy in real Pyodide, because opencv-python is not available in this page. The OpenCV-specific parts (imread, imshow, GaussianBlur) are read-only snippets, and where a real error message matters, it is described rather than shown.

The usual suspects

Channel order OpenCV is BGR, most others are RGB.
None images imread fails silently.
Coordinates Points are (x, y), arrays are [row, col].
Overflow uint8 wraps around at 256.
1 / 2

1. BGR versus RGB

OpenCV loads and stores color images in B, G, R order. Matplotlib, Pillow and most web code use R, G, B. Pass an OpenCV image straight to a library that expects RGB and red and blue swap: skin looks blue, skies look orange.

Python
import cv2
import matplotlib.pyplot as plt

img = cv2.imread("photo.jpg")                      # BGR
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))   # convert before showing
Python Channel order in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Habit: convert at the boundary, once, and name variables (img_bgr, img_rgb) so you can see which one you hold. See Color Spaces.

2. imread returns None

cv2.imread does not raise an exception when the file is missing, unreadable, or not an image. It returns None. The error shows up later, far from the cause, as something like AttributeError: 'NoneType' object has no attribute 'shape' or an assertion failure inside a cv2 function whose message mentions an empty image (!_src.empty()).

Python
import cv2

img = cv2.imread("photos/cat.jpg")
if img is None:
    raise FileNotFoundError("could not read photos/cat.jpg (path wrong, or not an image?)")

The usual causes: a wrong working directory (print os.getcwd()), a typo in the path, a file that is not an image, or non-ASCII characters in the path on some Windows setups (read the bytes with np.fromfile and decode with cv2.imdecode). Video has the same pattern: cap.read() returns (False, None) at the end of a stream.

Python Fail early on None

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Habit: wrap loading in a function that checks for None and names the path in the error message.

3. (x, y) versus (row, column)

Arrays are indexed img[row, column], which is img[y, x]. But OpenCV's drawing and geometry functions take points as (x, y), and sizes as (width, height), while img.shape is (height, width, channels). Mixing these up places things in the transposed position, and on a non-square image can place them outside the picture.

Python
h, w = img.shape[:2]
cv2.circle(img, (x, y), 5, (0, 255, 0), -1)     # (x, y)
pixel = img[y, x]                                # [row, column]
small = cv2.resize(img, (w // 2, h // 2))        # (width, height)
Python Row versus x

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Habit: write h, w = img.shape[:2] once, name your coordinates x and y, and index arrays only as img[y, x]. On a square image the swap hides; test with a wide one.

4. uint8 overflow

Images are uint8: values 0 to 255. NumPy arithmetic on them wraps around modulo 256, while OpenCV's cv2.add saturates (clamps at 255). So 200 + 100 is 44 with NumPy and 255 with OpenCV, and a bright area turns dark.

Python Wrap versus saturate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The subtraction case is just as common: 10 - 50 wraps up to 216. Habit: use cv2.add, cv2.subtract and cv2.addWeighted for pixel arithmetic, or convert to a wider type first. See Data Types, Ranges and Saturation.

5. Views versus copies

Assigning an image to a new name, or slicing it, does not copy the pixels. Both names refer to the same memory, so editing one changes the other. That is a feature for speed (see Making OpenCV Fast) and a trap when you wanted a backup.

Python Edits leak through views

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Habit: call .copy() whenever you will draw on or modify an image and still need the original. Functions such as cv2.rectangle draw in place on the array you pass, so drawing on img damages img unless you drew on img.copy().

6. Kernel sizes must be odd

cv2.GaussianBlur, cv2.medianBlur, cv2.adaptiveThreshold and the Sobel filters need an odd kernel (3, 5, 7, ...), so the kernel has a center pixel. An even size fails with an error message about the kernel size being odd and positive. Related: blockSize in adaptive thresholding must be odd and greater than 1, and ksize=0 in GaussianBlur means "compute it from sigma".

Python Why odd kernels

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Four pixels cannot be balanced around one pixel, which is why odd sizes are required. Habit: compute sizes with a helper like k = 2 * r + 1, so they are always odd.

7. imshow in a headless environment

cv2.imshow needs a display. On a server, in Docker, in WSL without a GUI, or with opencv-python-headless, it fails (typically with an error saying the function is not implemented or that it cannot connect to a display). Also remember that imshow shows nothing without a following cv2.waitKey, and a window closes when the program ends.

Python
import cv2

cv2.imshow("preview", img)
key = cv2.waitKey(0)            # without this the window never appears
cv2.destroyAllWindows()

On a machine without a display, write the image to a file and open that, or show it in a notebook with Matplotlib (after converting to RGB). Install opencv-python-headless on servers, and keep GUI calls out of code that runs there. See Installing OpenCV and Reading, Showing and Saving Images.

A debugging routine

When an output looks wrong, check the facts before guessing. A tiny helper that prints the facts about any image catches most of the problems above in seconds.

Python An image inspector

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look for the shape (is it (h, w) or (h, w, 3), and is height first?), the dtype (uint8 or float32?), the range (0 to 255, or 0 to 1?), and None. Then save intermediate images to files at each stage of your pipeline (cv2.imwrite("step1_gray.png", gray)) so you can find the stage where things go wrong.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does cv2.imread return when the file does not exist?

    imread returns None instead of raising, so check for None right after loading.
  2. 2. An image has shape (480, 640, 3). Which call draws a circle at x=600, y=100?

    OpenCV points are (x, y). The shape (480, 640) is height by width, so x can go up to 639 and y up to 479.
  3. 3. With uint8 arrays in NumPy, what is np.uint8(250) + np.uint8(10) in an array operation?

    NumPy uint8 arithmetic wraps modulo 256, so 260 becomes 4. cv2.add would saturate at 255.
  4. 4. You run b = a[0:100, 0:100] and then draw on b. What happens to a?

    Basic slicing returns a view sharing memory with a. Use .copy() for an independent image.
  5. 5. Why does GaussianBlur reject a kernel size of (4, 4)?

    Even kernels have no center pixel, so OpenCV requires odd, positive sizes.

Summary

  • OpenCV is BGR; convert to RGB at the boundary with other libraries.
  • imread returns None on failure; check it immediately and name the path.
  • Points and sizes are (x, y) and (width, height); arrays are [row, col] and (height, width).
  • uint8 arithmetic wraps in NumPy and saturates in cv2.add; widen the type or use cv2 functions.
  • Slices and assignments are views; use .copy() to keep the original; drawing functions work in place.
  • Use odd kernel sizes, and avoid imshow on machines without a display.
  • When stuck, print shape, dtype and range, and save intermediate images.

Next, learn to prove that your vision code stays correct in Testing Computer Vision Code.