Program to change RGB colour model to HSV colour model in Python

In this tutorial, we will learn how to write a program to change the RGB color model to the HSV color model in Python.
The RGB model describes the amount of Red, Green and Blue present in a color respectively. The HSV model describes color more like how a human eye perceives color.

Hue describes the color type. For example, Red, Yellow, Blue, etc.
Saturation is an indicator of the vibrancy of the color.
Finally, Value represents the brightness of the color.

Conversion from RGB to HSV

We can convert values from the RGB model to the HSV model as shown below.

RGB to HSV

Implementation in Python

We take user inputs for RGB values.
Next, we convert these to HSV.
Finally, we display H in degrees (°) and, S and V in percentage (%).

# Taking user inputs for R, G and B
R = int(input("Enter R value: "))
G = int(input("Enter G value: "))
B = int(input("Enter B value: "))

# Constraining the values to the range 0 to 1
R_dash = R / 255
G_dash = G / 255
B_dash = B / 255

# defining the following terms for convenience
Cmax = max(R_dash, G_dash, B_dash)
Cmin = min(R_dash, G_dash, B_dash)
delta = Cmax - Cmin

# hue calculation
if (delta == 0):
  H = 0
elif (Cmax == R_dash):
  H = (60 * (((G_dash  - B_dash) / delta) % 6))
elif (Cmax == G_dash):
  H = (60 * (((B_dash  - R_dash) / delta) + 2))
elif (Cmax == B_dash):
  H = (60 * (((R_dash  - G_dash) / delta) + 4))
 
# saturation calculation
if (Cmax == 0):
  S = 0
else:
  S = delta / Cmax

# value calculation
V = Cmax

# print output. H in degrees. S and V in percentage. 
# these values may also be represented from 0 to 255.
print("H = {:.1f}°".format(H))
print("S = {:.1f}%".format(S * 100))
print("V = {:.1f}%".format(V * 100))

Sample Input and Output

Enter R value: 43
Enter G value: 123
Enter B value: 32
H = 112.7°
S = 74.0%
V = 48.2%

Note: The values of H, S and V are also commonly displayed from 0 to 255.

Conclusion

In this tutorial, we learned how to write a program to change the RGB color model to the HSV color model in Python. We did this with the help of the formulae to convert RGB to HSV.

Leave a Reply

Your email address will not be published. Required fields are marked *