C中快速,优化和准确的RGB < - > HSB转换代码

Cru*_*han 2 c graphics colors

我正在寻找在纯C中快速,准确地实现RGB到HSB和HSB到RGB.请注意,我特别寻找色调,饱和度,亮度而不是 HSL(亮度).

当然,我已经广泛搜索了这一点,但速度在这里至关重要,我正在寻找有关可靠,快速,可靠代码的任何具体建议.

seh*_*ehe 5

这是标准C中的直接实现.

这是 - 没有进一步的背景 - 尽可能好.也许你想要更多地了解一下

  • 如何存储RGB样本(比特/像素开始!?)
  • 你如何存储你的像素数据(你想有效地转换更大的缓冲区,如果是这样,组织是什么)
  • 你想如何表示输出(我现在假设浮动)

我可以想出一个进一步优化的版本(也许可以很好地利用SSE4指令...)

所有这一切,当使用优化编译时,这不会太糟糕:

#include <stdio.h>
#include <math.h>

typedef struct RGB_t { unsigned char red, green, blue; } RGB;
typedef struct HSB_t { float hue, saturation, brightness; } HSB;

/*
 * Returns the hue, saturation, and brightness of the color.
 */
void RgbToHsb(struct RGB_t rgb, struct HSB_t* outHsb)
{
    // TODO check arguments

    float r = rgb.red / 255.0f;
    float g = rgb.green / 255.0f;
    float b = rgb.blue / 255.0f;
    float max = fmaxf(fmaxf(r, g), b);
    float min = fminf(fminf(r, g), b);
    float delta = max - min;
    if (delta != 0)
    {
        float hue;
        if (r == max)
        {
            hue = (g - b) / delta;
        }
        else
        {
            if (g == max)
            {
                hue = 2 + (b - r) / delta;
            }
            else
            {
                hue = 4 + (r - g) / delta;
            }
        }
        hue *= 60;
        if (hue < 0) hue += 360;
        outHsb->hue = hue;
    }
    else
    {
        outHsb->hue = 0;
    }
    outHsb->saturation = max == 0 ? 0 : (max - min) / max;
    outHsb->brightness = max;
}
Run Code Online (Sandbox Code Playgroud)

典型用法和测试:

int main()
{
    struct RGB_t rgb = { 132, 34, 255 };
    struct HSB_t hsb;

    RgbToHsb(rgb, &hsb);

    printf("RGB(%u,%u,%u) -> HSB(%f,%f,%f)\n", rgb.red, rgb.green, rgb.blue,
           hsb.hue, hsb.saturation, hsb.brightness);
    // prints: RGB(132,34,255) -> HSB(266.606354,0.866667,1.000000)

    return 0;
}
Run Code Online (Sandbox Code Playgroud)