Java 将 RGB 值转换为 HSV
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2399150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert RGB value to HSV
提问by marionmaiden
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.
我在互联网上找到了一种将 RGB 值转换为 HSV 值的方法。不幸的是,当值是 R=G=B 时,由于 0/0 操作,我得到了 NaN。
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?
你知道Java中是否有实现这种转换的方法,或者当我得到0/0除法以获得正确的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};
}