android convert from rgb to hsv and viceversa

Marco Di Scala picture Marco Di Scala · Jan 21, 2015 · Viewed 10k times · Source

someone can explain why the conversion from rgb to hsv doesn't give the same result when convert back from hsv to rgb?

int color = Color.rgb(206, 43, 55);

int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
System.out.println(red + ", " + green + ", " + blue);
//prints: 206, 43, 55 (as expected)

float[] hsv = new float[3];
Color.RGBToHSV(red, green, blue, hsv);

float hue = hsv[0];
float sat = hsv[1];
float val = hsv[2];

int outputColor = Color.HSVToColor(hsv);
red = Color.red(outputColor);
green = Color.green(outputColor);
blue = Color.blue(outputColor);
System.out.println(red + ", " + green + ", " + blue);

//prints: 206, 42, 54 (green and blue are changed)

Answer

Marco Di Scala picture Marco Di Scala · Jan 21, 2015

Finally I found the solution. There seems to be a strange approximation in the android implementation of android.graphics.Color.RGBToHSV. The approximated value is exactly the Hue that in this implementation goes from 0° to 360°.

I found the code of java.awt.Color.RGBtoHSB where the HUE goes from 0.0f to 1.0f and the conversion works well. So is not a float precision bug but an implementation bug, infact by multipling the Hue * 360f I get the correct HSV Hue value.