Images and Color in Python · Study

English translation

Execution conditions

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

Topics covered

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

Overall workflow

BGR image → RGB/HSV → mask → center coordinates

Color and array conventions

An image is an array of height×width×channels. OpenCV uses BGR channel order; Matplotlib uses RGB.

In OpenCV uint8 HSV, H ranges from 0…179 and S/V from 0…255, so do not directly compare these values with HSV values from other libraries.

From color to regions and coordinates

inRange creates a mask of pixels within the specified color range. Mask row indices correspond to y and column indices to x.

You can find the center by averaging the coordinates of detected pixels, but the center may be incorrect if multiple objects are combined or the background is also detected.

Connect MATLAB and Python images

MATLAB rgb2hsv and Python/OpenCV cvtColor serve the same purpose of converting color information. MATLAB images use RGB, while typical OpenCV camera arrays use BGR. Do not assume their HSV ranges are identical either.

Compare the colors, masks, and center coordinates for the same input image.

Worked example

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

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])
(120, 160, 3) uint8 [120 225 255]
실행 결과

Official documentation and data

Reference example

View more examples

Reference materials