Working with colors

Normally, when OpenCV obtains an image from a file or camera, it puts the image in the blue-green-red (BGR) color format. More specifically, the image is a 3D NumPy array in which image[y][x][0] is a pixel's blue value (in the range of 0 to 255), image[y][x][1] is its green value, and image[y][x][2] is its red value. The y and x indices start from the top-left corner of the image. If we convert an image into grayscale, it becomes a 2D NumPy array, in which image[y][x] is a pixel's grayscale value.

Let's write some utility functions in the ColorUtils module to work with color data. Our functions will use Python's standard math module and NumPy, as seen in the following import statements:

import math
import numpy

Let's write a function ...

Get Python Game Programming By Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.