对于一个uni项目,我正在制作自己的RGB到HSV色彩转换器。
这是我编写的代码
function calcSat() {
s = (maxRGB() - minRGB()) / maxRGB();
if (isNaN(s)) {
s = 0;
}
}
function calcVal() {
v = maxRGB();
}
function calcHue() {
var dr = (maxRGB() - r) /
maxRGB() - minRGB();
dr = Math.abs(dr);
var dg = (maxRGB() - g) /
maxRGB() - minRGB();
dg = Math.abs(dg);
var db = (maxRGB() - b) /
maxRGB() - minRGB();
db = Math.abs(db);
console.log("red:" + r, "green:" + g, "blue:" + b);
console.log("red d:" + dr, "green d:" + dg, "blue d:" + db);
if (s == 0) {
h = 0;
} else if (r == maxRGB && g == minRGB) {
h = 5 + db;
} else if (r == maxRGB && g != minRGB) {
h = 1 - dg;
} else if (g == maxRGB && b == minRGB) {
h = dr + 1;
} else if (g == maxRGB && b != minRGB) {
h = 3 - db;
} else if (r == maxRGB) {
h = 3 + dg;
} else {
h = 5 - dr;
}
h = h * 60;
}
您还可以在这里访问项目的副本:https://editor.p5js.org/eeu8cc/sketches/tYfnkWrA-
本质上,我试图创建3个函数来计算RGB颜色的色相,饱和度和值。一切运行正常,但我的输出完全错误。
据我所知,我已经正确地再现了方程。
对于感兴趣的人,这些屏幕截图来自here处的PDF。
任何帮助将不胜感激。
答案 0 :(得分:0)
为什么要为dr,dg,db取绝对值?并不是说应该有任何办法使它们消极,事实上,如果确实如此,我将其视为进一步指出了错误。
我是C和VHDL的人,而不是javascript,但肯定是
if (r == maxRGB && g == minRGB)
宁可像
if (r == maxRGB() && g == minRGB())
?
我假设==&&&绑定正确的方式,并且您不需要多余的花括号(我将它们放在C中只是因为它有一些晦涩难懂的案例,不值得记住)。
我也对浮点数相等比较的智慧提出质疑,因为很少会以结尾结尾。可以,如果定点类型的设计不是很好,但是IIRC javascript倾向于将FP用于任何令人痛苦的数字内容(如果不涉及寄存器刷新,X86的精度会过高,这可能会影响FP相等性)。如果您想继续学习数学,请参阅Goldburgs经典论文,或者,如果您想要更简单的https://floating-point-gui.de/
,请参阅这篇文章。maxRGB和minRGB不应采用参数(您不显示这些函数),但我希望它们采用r,g,b作为参数吗?
我倾向于处理广播中的颜色(我们生活在Y'CbCr空间中),但是我也认为您可能应该在进行转换之前转换为线性光空间,否则伽玛曲线会给您带来麻烦,但是这真是太好了。