Images and Color in Python

English translation

Learning objectives

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

Execution conditions

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

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

import numpy as np
import matplotlib.pyplot as plt
import cv2 as cv
image=np.full((120,160,3),220,dtype=np.uint8);image[30:90,50:110]=(255,30,30)
rgb=cv.cvtColor(image,cv.COLOR_BGR2RGB);hsv=cv.cvtColor(image,cv.COLOR_BGR2HSV)
fig,axes=plt.subplots(1,2);axes[0].imshow(image);axes[0].set_title('BGR as RGB');axes[1].imshow(rgb);axes[1].set_title('Correct RGB')
print(image.shape,image.dtype,hsv[60,80])

Record results and self-check

Representation:

shape:

dtype/value range:

Interpretation:

Points to check

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

mask=cv.inRange(hsv,np.array([100,80,50]),np.array([130,255,255]))
plt.figure();plt.imshow(mask,cmap='gray');print(np.count_nonzero(mask))
# TODO: Compare different brightness and background conditions.

Record results and self-check

Condition:

Detected pixel count:

Missed regions:

Falsely detected regions:

Points to check

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

yy,xx=np.nonzero(mask)
center=None if len(xx)==0 else (float(xx.mean()),float(yy.mean()))
print(center)
# TODO: Overlay the center on the image.

Record results and self-check

Scenario:

Center x:

Center y:

Detection valid:

Points to check

Official examples and data