Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android convert from rgb to hsv and viceversa

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)
like image 803
Marco Di Scala Avatar asked Jan 21 '15 01:01

Marco Di Scala


1 Answers

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.

like image 147
Marco Di Scala Avatar answered Sep 27 '22 16:09

Marco Di Scala