有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将RGB值转换为HSV

我在互联网上找到了一种将RGB值转换为HSV值的方法。 不幸的是,当值为R=G=B时,由于0/0操作,我得到了一个NaN

您知道Java中是否有实现这种转换的方法,或者当我得到0/0除法以获得正确的HSV值时,我必须做什么

下面是我的方法,改编自互联网上的一些代码:

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

共 (1) 个答案

  1. # 1 楼答案

    我很确定你想要的是RGBtoHSB

    int r = ...
    int g = ... 
    int b = ...
    float[] hsv = new float[3];
    Color.RGBtoHSB(r,g,b,hsv)
    //hsv contains the desired values