Search code examples
pythonimagecolorsrgbhsv

How to convert hsv to rgb in python?


I don't know why, but it doesn't work.

I've tried the following code:

matplotlib.colors.hsv_to_rgb([[[220 / 255, 255 / 255, 255 / 255]]])

matplotlib.colors.hsv_to_rgb([[[(220 % 360) / 255, 255 / 255, 255 / 255]]])

matplotlib.colors.hsv_to_rgb([[[220, 255, 255]]])

# same with
cv2.cvtColor(np.uint8([[[120, 255, 255]]]), cv2.COLOR_HSV2RGB)

but when I plot it:

import matplotlib.pyplot as plt
plt.imshow(converted_color)
plt.show()

It's showing some random stuff

getting values from GIMP:

values from GIMP


final result

h, s, v = 270, 100, 100
r, g, b = np.multiply((colorsys.hsv_to_rgb(h/360, s/100, v/100)), 255)
crop[mask == 0] = [r, g, b]

ex e len t!


here is fixed cv2 solution. h - having 180 maximum. opencv as usual doing thing on his own way... -___-

h, s, v = 270, 100, 100
r, g, b = cv2.cvtColor(np.uint8([[[h / 2, (s/100)*255, (v/100)*255]]]), cv2.COLOR_HSV2RGB)[0][0]
crop[mask == 0] = [r, g, b]

Solution

  • Try using colorsys:

    import colorsys
    colorsys.hsv_to_rgb(0.5, 0.5, 0.4)
    

    Output:

    (0.2, 0.4, 0.4)
    

    Edit

    An example could be:

    import matplotlib
    import matplotlib.pyplot as plt
    import colorsys
    
    h, s, v = 0.83, 1.0, 0.50
    #RGB from 0 to 1 NO from 0 to 255
    r, g, b = colorsys.hsv_to_rgb(h, s, v)
    print(r, g, b)
    
    rect1 = matplotlib.patches.Rectangle((-200, -100), 400, 200, color=[r, g, b])
    plt.axes().add_patch(rect1)
    plt.show()
    

    enter image description here

    To see why you may be having troubles in displaying color using imshow refer to: Printing one color using imshow