Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert RGB value to HSV

Tags:

java

image

rgb

hsv

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};
}
like image 421
marionmaiden Avatar asked Mar 08 '10 03:03

marionmaiden


People also ask

How do you convert RGB to HSV?

Converting RGB to HSVH = 360 - cos-1[ (R - ½G - ½B)/√R² + G² + B² - RG - RB - GB ] if B > G. Inverse cosine is calculated in degrees.

Why do we convert RGB to HSV?

R, G, B in RGB are all co-related to the color luminance( what we loosely call intensity),i.e., We cannot separate color information from luminance. HSV or Hue Saturation Value is used to separate image luminance from color information. This makes it easier when we are working on or need luminance of the image/frame.

Can HSV color be converted to RGB?

RGB = hsv2rgb( HSV ) converts the hue, saturation, and value (HSV) values of an HSV image to red, green, and blue values of an RGB image. rgbmap = hsv2rgb( hsvmap ) converts an HSV colormap to an RGB colormap.

How do I convert an image from RGB to HSV in Python?

Thus, to convert to HSV, we should use the COLOR_BGR2HSV code. As output, the cvtColor will return the converted image, which we will store in a variable. After this, we will display both images. To show each image, we simply need to call the imshow function.


1 Answers

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
like image 189
job Avatar answered Oct 03 '22 21:10

job