pythonrgbhsv

RGB to HSV using colorsys


i am trying to make a tracking program that takes an image and displays where the the object with the specified color is:

example: https://i.sstatic.net/u202H.jpg

to do this i am using RGB right now but it is realy hard to work with it so i want to convert it into a hue so it is easier to work with. i am trying to use colorsys but after doing some research i have no idea what parameters it wants in and what it gives. i have tried to get a match using colorizer.org but i get some nonsence.

>>> import colorsys
>>> colorsys.rgb_to_hsv(45,201,18)
(0.3087431693989071, 0.9104477611940298, 201)

alredy the colorsys is not acting as documented because at https://docs.python.org/2/library/colorsys.html it says that the output is always a float between 0 and 1, but the value is 201. that also is impossible as in standard HSV the value is between 0 and 100.

my questions are: what does colorsys expect as an input? how do i convert the output to standard HSV? (Hue = 0-360, saturation = 0-100, value = 0-100)


Solution

  • Coordinates in all of these color spaces are floating point values. In the YIQ space, the Y coordinate is between 0 and 1, but the I and Q coordinates can be positive or negative. In all other spaces, the coordinates are all between 0 and 1.

    https://docs.python.org/3/library/colorsys.html

    You must scale from [0, 255] to [0, 1], or divide your RGB values with 255. If using python 2 make sure not to do floor division.


    Here is an example code inspired by Pillow's getcolor.

    from colorsys import rgb_to_hsv
    
    def to_hsv(r, g, b):
      h, s, v = rgb_to_hsv(r / 255, g / 255, b / 255)
      return int(h * 255), int(s * 255), int(v * 255)
    
    rgb = (47, 207, 227)
    
    # This is one usage, which returns (132, 202, 227).
    hsv_example_1 = to_hsv(*rgb)
    
    # This is another usage, which returns (132, 202, 227).
    hsv_example_2 = to_hsv(rgb[0], rgb[1], rgb[2])