How to convert RGB to HSV in Python?

Python – Convert RGB to HSV

To convert RGB color values to HSV color values in Python, import colorsys library, call rgb_to_hsv() function, and pass the Red, Green, and Blue values as arguments.

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

The Red, Blue, and Green values must be normalised to the range [0, 1] prior to conversion for input to rgb_to_hsv() function.

Examples

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

Python Program

import colorsys

(r, g, b) = (0.2, 0.4, 0.4)
(h, s, v) = colorsys.rgb_to_hsv(r, g, b)
print('HSV : ', h, s, v)
Run

Output

HSV :  0.5 0.5 0.4

Convert RGB to HSV with values in 8-bit Ranges

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

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
(r, g, b) = (142, 244, 85)
#normalize
(r, g, b) = (r / 255, g / 255, b / 255)
#convert to hsv
(h, s, v) = colorsys.rgb_to_hsv(r, g, b)
#expand HSV range
(h, s, v) = (int(h * 179), int(s * 255), int(v * 255))
print('HSV : ', h, s, v)
Run

Output

HSV :  48 166 244

Summary

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