Images and Color in Python

English translation

Compare visual appearance and array values to see how brightness, color, and size transformations change information needed for detection.

Before practice

01 Why can the same image appear in different colors?

Description

OpenCV uses BGR channel order, while Matplotlib uses RGB.

02 Can a brightness change cause the same color to be missed?

Description

Set the color range and brightness criterion separately, and compare masks before and after conversion.

Execution conditions

Use opencv-python-headless, NumPy, and Matplotlib. A camera is not required for the basic activities.

Practice

Preview practice notebookDownload practice notebook

1. From arrays to images

Starting conditions

Draw a blue rectangle in a 120×160 BGR image, and convert it to RGB, grayscale, and HSV.

Procedure

  1. Check the original array's shape, dtype, and range.
  2. Display the same image correctly in Matplotlib and compare with a deliberately altered channel order.

Results to retain

Items to record and points to check
Representation
shape
dtype/value range
Interpretation

Points to check

  • Have you avoided displaying a BGR array as RGB?
  • Did you check that H ranges from 0…179 in OpenCV uint8 HSV?

2. Find objects by color range

Starting conditions

Use the blue HSV range H=100H=100…130, S≥80, V≥50.

Procedure

  1. Create a mask using inRange and display it beside the original.
  2. Lower image brightness and detect regions using the same criterion.
  3. Add noise or a background with a similar color and examine the resulting errors.

Results to retain

Items to record and points to check
Condition
Detected pixel count
Missed regions
Falsely detected regions

Points to check

  • Did you keep the meanings of RGB and HSV channels distinct?
  • Have you avoided judging accuracy solely by the number of detected pixels?

3. Pass coordinates to the next stage

Starting conditions

Calculate the center of the region detected in the mask in pixel coordinates.

Procedure

  1. Describe the relationship between row/column indices and x/y coordinates.
  2. Overlay the center point on the image to check its coordinates.
  3. Define the return value when no regions are detected.

Results to retain

Items to record and points to check
Scenario
Center x
Center y
Detection valid

Points to check

  • If using 0,0 to indicate missed detection, have you distinguished it from an actual object at the upper left?
  • Did you preserve the relationship of rows to y and columns to x?

Official examples and data