Question

I am trying to perform a color conversion between RGB and HSV and back to RGB. It's for an HSV color picker program I am creating. I retrieve the HSV components. I want to set the new saturation strictly for my color, so set the Saturation value equal to the requested value. Then I convert it back into RGB. However, the value of the Hue has changed and I did not request it. Furthermore, if I constantly move my Saturation slider, the hue eventually lines the color up with Cyan, Yellow, or Magenta, which have the hues of 60, 180, and 300. Is there a way for the hue to not change when setting saturation?

NOTE: getHue, getSaturation, and getValue are retrieving the colorCode's HSV component

public void setSaturation(float s)
{
    float hsv[];
    hsv = new float[3];
    Log.i("Before change",String.valueOf("H: "+getHue()+" S: "+getSaturation()+" V: "+getValue()));
    Color.RGBToHSV(getRed(), getGreen(), getBlue(), hsv);
    hsv[1] = s;
    colorCode = Color.HSVToColor(hsv);
    Log.i("After change",String.valueOf("H: "+getHue()+" S: "+getSaturation()+" V: "+getValue()));
}

Before change(21558): H: 28.771929 S: 0.67058825 V: 1.0

After change(21558): H: 28.928572 S: 0.65882355 V: 1.0

Was it helpful?

Solution

the transformation from rgb to hsv is non linear and float precision is not high enough to get a lossless transformation. Here you can find an integer based conversion solution which is lossless. Its c++ but should be easy enough to convert to java.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top