How to convert HSV to RGB in Python?

Contents

Python – Convert HSV to RGB

To convert HSV color values to RGB color values in Python, import colorsys library, call hsv_to_rgb() function, and pass the Hue, Saturation, and Value values as arguments.

hsv_to_rgb() function takes Hue, Saturation, and Value values as arguments, and returns a tuple containing Red, Blue, and Green values.

The Hue, Saturation, and Value values must be normalised to the range [0, 1] prior to conversion for input to hsv_to_rgb() function.

Examples

In the following program, we take a HSV value and convert it to an RGB value.

Python Program

import colorsys

(h, s, v) = (0.2, 0.4, 0.4)
(r, g, b) = colorsys.hsv_to_rgb(h, s, v)
print('RGB :', r, g, b)
Run Code Copy

Output

RGB : 0.368 0.4 0.24

Convert HSV to RGB with values in 8-bit Ranges

In the following program, we are getting HSV values in the range specified in the below table, and we shall convert it to RGB values to the ranges mentioned below.

ComponentRange
R (Red)[0, 255]
G (Green)[0, 255]
B (Blue)[0, 255]
H (Hue)[0, 179]
S (Saturation)[0, 255]
V (Value)[0, 255]

Python Program

import colorsys

# Input
(h, s, v) = (142, 244, 85)

# Normalize
(h, s, v) = (h / 255, s / 255, v / 179)

# Convert to RGB
(r, g, b) = colorsys.hsv_to_rgb(h, s, v)

# Expand RGB range
(r, g, b) = (int(r * 255), int(g * 255), int(b * 255))
print('RGB :', r, g, b)
Run Code Copy

Output

RGB : 5 81 121

Summary

In this Python Tutorial, we learned how to convert a HSV color value to an RGB color value, using colorsys library.

Related Tutorials

Code copied to clipboard successfully 👍