20

I've found a method on the Internet to convert RGB values to HSV values. Unfortunately, when the values are R=G=B, I'm getting a NaN, because of the 0/0 operation.

Do you know if there is an implemented method for this conversion in Java, or what do I have to do when I get the 0/0 division to get the right value of the HSV?

Here comes my method, adapted from some code on the Internet:

public static double[] RGBtoHSV(double r, double g, double b){

    double h, s, v;

    double min, max, delta;

    min = Math.min(Math.min(r, g), b);
    max = Math.max(Math.max(r, g), b);

    // V
    v = max;

     delta = max - min;

    // S
     if( max != 0 )
        s = delta / max;
     else {
        s = 0;
        h = -1;
        return new double[]{h,s,v};
     }

    // H
     if( r == max )
        h = ( g - b ) / delta; // between yellow & magenta
     else if( g == max )
        h = 2 + ( b - r ) / delta; // between cyan & yellow
     else
        h = 4 + ( r - g ) / delta; // between magenta & cyan

     h *= 60;    // degrees

    if( h < 0 )
        h += 360;

    return new double[]{h,s,v};
}
Martin
  • 37,119
  • 15
  • 73
  • 82
marionmaiden
  • 3,250
  • 8
  • 33
  • 50
  • For anyone interested in the actual answer to the question, I believe when r=g=b, hsv = [0,0,r/255.0]. The hue is arbitrary, the saturation is 0 (it's a shade of gray) and the value however bright the r=g=b value is. – thomas88wp Jul 26 '13 at 00:54

1 Answers1

61

I'm pretty sure what you want is RGBtoHSB

int r = ...
int g = ... 
int b = ...
float[] hsv = new float[3];
Color.RGBtoHSB(r,g,b,hsv)
//hsv contains the desired values
job
  • 9,003
  • 7
  • 41
  • 50
  • what's the difference between HSV and HSB? – marionmaiden Mar 08 '10 at 20:27
  • 8
    Just a different name for the third value. Hue, Saturation, and Value or Brightness. – job Mar 09 '10 at 00:17
  • 6
    [No, HSB is not the same as HSL!](http://en.wikipedia.org/wiki/HSL_and_HSV) HSB is the same as HSV, because V - value may be called also B - brightness. But HSL gives you simillar idea of color space as HSV, but, just read it from the link. – Marcin Nov 19 '12 at 15:17