以下是一个C语言中快速、优化和准确的RGB <-> HSB(HSV)转换代码:
#include<stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct {
float h;
float s;
float b;
} HSB;
typedef struct {
float r;
float g;
float b;
} RGB;
HSB rgb2hsb(RGB in)
{
float hue, saturation, brightness;
float r = in.r;
float g = in.g;
float b = in.b;
float cmax = (r > g) ? r : g;
if (b > cmax) cmax = b;
float cmin = (r < g) ? r : g;
if (b < cmin) cmin = b;
float delta = cmax - cmin;
brightness = cmax;
if (delta == 0) {
hue = 0;
saturation = 0;
} else {
saturation = delta / cmax;
if (r == cmax)
hue = (g - b) / delta;
else if (g == cmax)
hue = 2 + (b - r) / delta;
else
hue = 4 + (r - g) / delta;
hue *= 60;
if (hue < 0)
hue += 360;
}
HSB out;
out.h = hue;
out.s = saturation;
out.b = brightness;
return out;
}
RGB hsb2rgb(HSB in)
{
float hue = in.h;
float saturation = in.s;
float brightness = in.b;
float h = hue / 60;
int i = floor(h);
float f = h - i;
float p = brightness * (1 - saturation);
float q = brightness * (1 - saturation * f);
float t = brightness * (1 - saturation * (1 - f));
float r, g, b;
switch (i) {
case 0:
r = brightness;
g = t;
b = p;
break;
case 1:
r = q;
g = brightness;
b = p;
break;
case 2:
r = p;
g = brightness;
b = t;
break;
case 3:
r = p;
g = q;
b = brightness;
break;
case 4:
r = t;
g = p;
b = brightness;
break;
default:
r = brightness;
g = p;
b = q;
break;
}
RGB out;
out.r = r;
out.g = g;
out.b = b;
return out;
}
int main()
{
RGB rgb;
HSB hsb;
rgb.r = 255;
rgb.g = 0;
rgb.b = 0;
hsb = rgb2hsb(rgb);
printf("HSB: h = %.2f, s = %.2f, b = %.2f\n", hsb.h, hsb.s, hsb.b);
hsb.h = 120;
hsb.s = 1;
hsb.b = 1;
rgb = hsb2rgb(hsb);
printf("RGB: r = %.2f, g = %.2f, b = %.2f\n", rgb.r, rgb.g, rgb.b);
return 0;
}
这段代码中,我们定义了两个结构体,分别是RGB和HSB,用于存储颜色值。然后,我们实现了两个函数,分别是rgb2hsb和hsb2rgb,用于实现RGB到HSB的转换和HSB到RGB的转换。最后,我们在main函数中测试了这两个函数的正确性。
这段代码可以作为一个通用的RGB到HSB转换器,它可以在各种应用程序中使用,例如图像处理、图形用户界面、游戏开发等。
领取专属 10元无门槛券
手把手带您无忧上云