Last Updated: 

Exploring MicroPython's `colorsys` Module

MicroPython is a lean and efficient implementation of the Python 3 programming language that includes a small subset of the Python standard library. One such useful module is colorsys, which provides functions for converting colors between different color models. Understanding color models and how to convert between them is essential in various applications, such as LED lighting control, graphics programming, and data visualization. In this blog post, we will delve into the fundamental concepts of the colorsys module in MicroPython, explore its usage methods, common practices, and best practices.

Table of Contents#

  1. Fundamental Concepts of Color Models
  2. MicroPython colorsys Module Overview
  3. Usage Methods
  4. Common Practices
  5. Best Practices
  6. Conclusion
  7. References

Fundamental Concepts of Color Models#

RGB (Red, Green, Blue)#

The RGB color model is an additive color model in which red, green, and blue light are added together in various ways to reproduce a broad array of colors. In this model, each color is represented by a triplet of values, typically ranging from 0 to 255, indicating the intensity of red, green, and blue components respectively. For example, (255, 0, 0) represents pure red, (0, 255, 0) represents pure green, and (0, 0, 255) represents pure blue.

HSV (Hue, Saturation, Value)#

The HSV color model is a cylindrical-coordinate representation of colors.

  • Hue: Represents the pure color on the color wheel, ranging from 0 to 360 degrees. For example, 0 degrees represents red, 120 degrees represents green, and 240 degrees represents blue.
  • Saturation: Indicates the purity or vividness of the color. A saturation of 0 means the color is completely gray, while a saturation of 1 means the color is fully saturated.
  • Value: Represents the brightness of the color. A value of 0 means the color is black, while a value of 1 means the color is at its maximum brightness.

HLS (Hue, Lightness, Saturation)#

The HLS color model is similar to the HSV model but uses lightness instead of value.

  • Hue: Similar to the HSV model, it represents the pure color on the color wheel.
  • Lightness: Determines how light or dark the color is. A lightness of 0 means the color is black, 0.5 means the color is at its normal saturation, and 1 means the color is white.
  • Saturation: Similar to the HSV model, it indicates the purity or vividness of the color.

MicroPython colorsys Module Overview#

The colorsys module in MicroPython provides functions for converting colors between the RGB, HSV, and HLS color models. The main functions in the module are:

  • rgb_to_hsv(r, g, b): Converts an RGB color to an HSV color.
  • hsv_to_rgb(h, s, v): Converts an HSV color to an RGB color.
  • rgb_to_hls(r, g, b): Converts an RGB color to an HLS color.
  • hls_to_rgb(h, l, s): Converts an HLS color to an RGB color.

Usage Methods#

Converting RGB to HSV#

import colorsys
 
# Define an RGB color
r = 255
g = 0
b = 0
 
# Normalize RGB values to the range [0, 1]
r_normalized = r / 255.0
g_normalized = g / 255.0
b_normalized = b / 255.0
 
# Convert RGB to HSV
h, s, v = colorsys.rgb_to_hsv(r_normalized, g_normalized, b_normalized)
 
print(f"RGB: ({r}, {g}, {b})")
print(f"HSV: ({h}, {s}, {v})")

In this example, we first define an RGB color (255, 0, 0) which represents pure red. We then normalize the RGB values to the range [0, 1] because the rgb_to_hsv function expects input values in this range. Finally, we convert the RGB color to an HSV color and print the results.

Converting HSV to RGB#

import colorsys
 
# Define an HSV color
h = 0
s = 1
v = 1
 
# Convert HSV to RGB
r_normalized, g_normalized, b_normalized = colorsys.hsv_to_rgb(h, s, v)
 
# Convert normalized RGB values back to the range [0, 255]
r = int(r_normalized * 255)
g = int(g_normalized * 255)
b = int(b_normalized * 255)
 
print(f"HSV: ({h}, {s}, {v})")
print(f"RGB: ({r}, {g}, {b})")

In this example, we define an HSV color (0, 1, 1) which represents pure red. We then convert the HSV color to an RGB color using the hsv_to_rgb function. Finally, we convert the normalized RGB values back to the range [0, 255] and print the results.

Common Practices#

LED Lighting Control#

One common use case of the colorsys module is in LED lighting control. LEDs are often controlled using RGB values, but it can be more intuitive to specify colors using the HSV or HLS color models. For example, you can create a rainbow effect on an LED strip by incrementing the hue value in the HSV color model and converting it to RGB values.

import colorsys
import time
from machine import Pin
import neopixel
 
# Initialize the NeoPixel strip
pin = Pin(4, Pin.OUT)
np = neopixel.NeoPixel(pin, 8)
 
# Generate a rainbow effect
while True:
    for i in range(360):
        h = i / 360.0
        s = 1
        v = 1
        r_normalized, g_normalized, b_normalized = colorsys.hsv_to_rgb(h, s, v)
        r = int(r_normalized * 255)
        g = int(g_normalized * 255)
        b = int(b_normalized * 255)
        for j in range(np.n):
            np[j] = (r, g, b)
        np.write()
        time.sleep(0.01)

In this example, we use the colorsys module to generate a rainbow effect on an 8-pixel NeoPixel LED strip. We increment the hue value from 0 to 360 degrees and convert it to RGB values using the hsv_to_rgb function. We then set the color of each pixel on the LED strip to the calculated RGB values and update the strip.

Data Visualization#

The colorsys module can also be used in data visualization to represent data using different colors. For example, you can map the values of a dataset to different hues in the HSV color model and convert them to RGB values for display.

import colorsys
import matplotlib.pyplot as plt
import numpy as np
 
# Generate some sample data
data = np.random.rand(10)
 
# Map data values to hues in the HSV color model
hues = data
s = 1
v = 1
 
# Convert HSV to RGB
colors = []
for h in hues:
    r_normalized, g_normalized, b_normalized = colorsys.hsv_to_rgb(h, s, v)
    r = int(r_normalized * 255)
    g = int(g_normalized * 255)
    b = int(b_normalized * 255)
    colors.append((r / 255, g / 255, b / 255))
 
# Plot the data with different colors
plt.bar(range(len(data)), data, color=colors)
plt.show()

In this example, we generate some sample data and map the values to different hues in the HSV color model. We then convert the HSV colors to RGB colors and use them to plot the data using the matplotlib library.

Best Practices#

Normalize Input Values#

When using the functions in the colorsys module, make sure to normalize the input values to the range [0, 1]. The functions expect input values in this range, and using values outside this range may lead to unexpected results.

Error Handling#

Although the colorsys module functions do not raise explicit errors for invalid input values, it is a good practice to validate the input values before passing them to the functions. For example, make sure that the hue value is in the range [0, 1], the saturation value is in the range [0, 1], and the value/lightness value is in the range [0, 1].

Performance Considerations#

Converting colors between different color models can be computationally expensive, especially if you need to perform a large number of conversions. If performance is a concern, consider pre-calculating the color conversions and storing the results in a lookup table.

Conclusion#

The colorsys module in MicroPython provides a convenient way to convert colors between different color models. By understanding the fundamental concepts of color models and how to use the functions in the colorsys module, you can create more intuitive and visually appealing applications, such as LED lighting control and data visualization. Remember to follow the best practices, such as normalizing input values and handling errors, to ensure the reliability and performance of your code.

References#