首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从RGB中获取色调的最快公式

从RGB中获取色调的最快公式
EN

Stack Overflow用户
提问于 2014-04-15 16:59:41
回答 6查看 62.3K关注 0票数 40

如果给出的值为红色、绿色和蓝色,范围从0到255,那么获得色调值的最快计算是什么?这个公式将用于640x480图像的每一个像素的30 This (920万次每秒),所以每一点速度优化都有帮助。

我见过其他公式,但我不满意它们涉及的步骤有多少。我在寻找一个实际的公式,而不是内置的库函数。

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2014-04-15 21:04:18

  1. 将RGB值转换为0-1范围,这可以通过对8位颜色深度(r、g、b-给出的值)除以255来实现: R=r/ 255 = 0.09 G=g/ 255 = 0.38 B=b/ 255 = 0.46
  2. 求R,G,B的最小值和最大值。
  3. 取决于什么RGB颜色通道是最大值。这三个不同的公式是:
代码语言:javascript
复制
- If Red is max, then `Hue = (G-B)/(max-min)`
- If Green is max, then `Hue = 2.0 + (B-R)/(max-min)`
- If Blue is max, then `Hue = 4.0 + (R-G)/(max-min)`

您得到的色调值需要乘以60,才能将其转换为颜色圈上的度。如果色调变成负值,你需要增加360度,因为一个圆有360度。

这是整篇文章

票数 64
EN

Stack Overflow用户

发布于 2014-10-07 09:55:41

除了Umriyaev的答复外:

如果只需要色调,则不需要将0-255的范围颜色与255进行分割。

的结果。(green - blue) / (max - min)对于任何范围都是一样的(当然,只要颜色在相同的范围内)。

下面是获取Hue的java示例:

代码语言:javascript
复制
public int getHue(int red, int green, int blue) {

    float min = Math.min(Math.min(red, green), blue);
    float max = Math.max(Math.max(red, green), blue);

    if (min == max) {
        return 0;
    }

    float hue = 0f;
    if (max == red) {
        hue = (green - blue) / (max - min);

    } else if (max == green) {
        hue = 2f + (blue - red) / (max - min);

    } else {
        hue = 4f + (red - green) / (max - min);
    }

    hue = hue * 60;
    if (hue < 0) hue = hue + 360;

    return Math.round(hue);
}

编辑:添加检查min和max是否相同,因为在本例中不需要计算的其余部分,并避免除以0(请参阅注释)

编辑:修正java错误

票数 31
EN

Stack Overflow用户

发布于 2015-09-06 11:31:31

代码语言:javascript
复制
function rgbToHue(r, g, b) {
    // convert rgb values to the range of 0-1
    var h;
    r /= 255, g /= 255, b /= 255;

    // find min and max values out of r,g,b components
    var max = Math.max(r, g, b), min = Math.min(r, g, b);

    // all greyscale colors have hue of 0deg
    if(max-min == 0){
        return 0;
    }

    if(max == r){
        // if red is the predominent color
        h = (g-b)/(max-min);
    }
    else if(max == g){
        // if green is the predominent color
        h = 2 +(b-r)/(max-min);
    }
    else if(max == b){
        // if blue is the predominent color
        h = 4 + (r-g)/(max-min);
    }

    h = h*60; // find the sector of 60 degrees to which the color belongs
    // https://www.pathofexile.com/forum/view-thread/1246208/page/45 - hsl color wheel

    // make sure h is a positive angle on the color wheel between 0 and 360
    h %= 360;
    if(h < 0){
        h += 360;
    }

    return Math.round(h);
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23090019

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档