Convert RGB value to HSV

Posted by marionmaiden on Stack Overflow See other posts from Stack Overflow or by marionmaiden
Published on 2010-03-08T03:37:42Z Indexed on 2010/03/08 3:51 UTC
Read the original article Hit count: 604

Filed under:
|
|
|
|

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};
}

© Stack Overflow or respective owner

Related posts about java

Related posts about image