views:

252

answers:

2

Hi,

I want to convert RGB values to HSV using python. I got some code samples, which gave the result with the S and V values greater than 100. (example : http://code.activestate.com/recipes/576554-covert-color-space-from-hsv-to-rgb-and-rgb-to-hsv/ ) . anybody got a better code which convert RGB to HSV and vice versa

thanks

+6  A: 

Did you try using the colorsys library?

The colorsys module defines bidirectional conversions of color values between colors expressed in the RGB (Red Green Blue) color space used in computer monitors and three other coordinate systems: YIQ, HLS (Hue Lightness Saturation) and HSV (Hue Saturation Value)

Example (taken from the above link):

>>> import colorsys
>>> colorsys.rgb_to_hsv(.3, .4, .2)
(0.25, 0.5, 0.4)
>>> colorsys.hsv_to_rgb(0.25, 0.5, 0.4)
(0.3, 0.4, 0.2)
Eli Bendersky
how to convert integer values like (220, 20, 60) into float to use with colorsys?
Sreejith
@sree01: would the fraction out of 256 work for you? i.e. `val_in_int / float(256)`?
Eli Bendersky
thanks for the reply
Sreejith
@Eli: the divisor should be 255, since the range for the `colorsys` functions is `[0.0…1.0]`.
ΤΖΩΤΖΙΟΥ
A: 

What values of R, G, and B did you put in, and what values of H, S, and V that look erroneous did you get out?

The code you link to, like colorsys, expects float values between 0.0 and 1.0. If you call it with integer values in the 0-to-255 range, you'll get bogus results. It should work fine if you give it the input values it expects.

(It is a distinct failure of that code sample that it does not actually document what sorts of inputs it expects.)

Brooks Moses