I need to know details of how java implements the function Color.RGBtoHSB(r, g, b, hsb). Does they normalize r,g,b

StackOverflow https://stackoverflow.com/questions/12216583

I do not know whether Color.RGBtoHSB(r, g, b, hsb) function normalize the r,g,b before converting it to H,S,B or where i can get the java implementation of their built in functions.

有帮助吗?

解决方案

Here is the implementation, from Color class source code directly:

public static float[] RGBtoHSB(int r, int g, int b, float[] hsbvals) {
float hue, saturation, brightness;
if (hsbvals == null) {
    hsbvals = new float[3];
}
    int cmax = (r > g) ? r : g;
if (b > cmax) cmax = b;
int cmin = (r < g) ? r : g;
if (b < cmin) cmin = b;

brightness = ((float) cmax) / 255.0f;
if (cmax != 0)
    saturation = ((float) (cmax - cmin)) / ((float) cmax);
else
    saturation = 0;
if (saturation == 0)
    hue = 0;
else {
    float redc = ((float) (cmax - r)) / ((float) (cmax - cmin));
    float greenc = ((float) (cmax - g)) / ((float) (cmax - cmin));
    float bluec = ((float) (cmax - b)) / ((float) (cmax - cmin));
    if (r == cmax)
    hue = bluec - greenc;
    else if (g == cmax)
        hue = 2.0f + redc - bluec;
        else
    hue = 4.0f + greenc - redc;
    hue = hue / 6.0f;
    if (hue < 0)
    hue = hue + 1.0f;
}
hsbvals[0] = hue;
hsbvals[1] = saturation;
hsbvals[2] = brightness;
return hsbvals;
}

其他提示

Just open up Eclipse - Ctrl+Shift+T (open type), type in Color, find the one in java.awt - and voila. Works for most built in types.

RGB isn't normalized first. It's normalized during and generally just into the correct ranges. So brightness is the largest component and brightness is normalized from 0-255 range to 0-1 range. Saturation is like this as well, it's the distance from the largest component to the smallest component and squeezed into a 0-1 range. And hue is the angle in the color wheel. But, no it's converted directly into HSV and not normalized through something like sRGB (sRGB is RGB/255 and normalized into 0-1 range).

But, you shouldn't really need to know this at all. It converts into HSB. Can you get rounding errors if you convert back and forth a bunch. Sure, you can. Other than this it doesn't matter if it scales RGB to 1 or 1,000,000, it converts to a completely different way of representing colors in ranges between 0-1.

Note: the hue returned from Color.RGBtoHSB is normalized between 0.0 and 1.0, not between 0 and 255: ```

public static void main(String[] args) {
        float[] hsbvals = new float[3];
        Random random = new Random();
        for(int i=0;i<20;i++) {
            Color.RGBtoHSB(random.nextInt(256),random.nextInt(256),random.nextInt(256),hsbvals);
            System.out.println(Arrays.toString(hsbvals));
        }
    }

```

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top