Here is a straightforward implementation in standard C.
This is - without further context - as good as it can get. Perhaps you care to shed some more light on
- how you store your RGB samples (bits/pixel to begin with !?)
- how you store your pixel data (do you want to efficiently transform larger buffers, if so, what is the organization)
- how you want to represent the output (I assumed floats for now)
I could come up with a further optimized version (perhaps one that utilisze SSE4 instructions nicely...)
All that said, when compiled with optimizations, this doesn't work too badly:
#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;
}
Typical usage and test:
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;
}