c语言比例法颜色,颜色空间RGB与 色调、饱和度、亮度(ESL)转换的完整C语言算法...
时间: 2023-12-18 19:05:00 浏览: 172
颜色空间转换
4星 · 用户满意度95%
以下是C语言中实现颜色比例法、RGB与ESL转换的完整算法:
颜色比例法:
```c
#include <stdio.h>
int main() {
float r, g, b;
printf("Enter RGB values (0-255): ");
scanf("%f %f %f", &r, &g, &b);
// normalize the RGB values
r /= 255;
g /= 255;
b /= 255;
// calculate the maximum RGB value
float cmax = (r > g) ? r : g;
if (b > cmax) {
cmax = b;
}
// calculate the minimum RGB value
float cmin = (r < g) ? r : g;
if (b < cmin) {
cmin = b;
}
// calculate the difference between max and min
float diff = cmax - cmin;
// calculate hue
float hue = 0;
if (diff == 0) {
hue = 0;
} else if (cmax == r) {
hue = (60 * ((g - b) / diff) + 360) % 360;
} else if (cmax == g) {
hue = (60 * ((b - r) / diff) + 120) % 360;
} else if (cmax == b) {
hue = (60 * ((r - g) / diff) + 240) % 360;
}
// calculate saturation
float saturation = (cmax == 0) ? 0 : (diff / cmax) * 100;
// calculate lightness
float lightness = (cmax + cmin) / 2 * 100;
printf("HSL values: %.2f %.2f %.2f\n", hue, saturation, lightness);
return 0;
}
```
RGB与ESL转换:
```c
#include <stdio.h>
int main() {
float r, g, b;
printf("Enter RGB values (0-255): ");
scanf("%f %f %f", &r, &g, &b);
// normalize the RGB values
r /= 255;
g /= 255;
b /= 255;
// calculate the maximum RGB value
float cmax = (r > g) ? r : g;
if (b > cmax) {
cmax = b;
}
// calculate the minimum RGB value
float cmin = (r < g) ? r : g;
if (b < cmin) {
cmin = b;
}
// calculate the difference between max and min
float diff = cmax - cmin;
// calculate hue
float hue = 0;
if (diff == 0) {
hue = 0;
} else if (cmax == r) {
hue = (60 * ((g - b) / diff) + 360) % 360;
} else if (cmax == g) {
hue = (60 * ((b - r) / diff) + 120) % 360;
} else if (cmax == b) {
hue = (60 * ((r - g) / diff) + 240) % 360;
}
// calculate saturation
float saturation = (cmax == 0) ? 0 : (diff / cmax) * 100;
// calculate lightness
float lightness = (cmax + cmin) / 2 * 100;
// convert to ESL
float hue_prime = hue / 60;
float chroma = (1 - fabs(2 * lightness - 1)) * saturation;
float x = chroma * (1 - fabs(fmod(hue_prime, 2) - 1));
float m = lightness - chroma / 2;
// convert to RGB
float r1, g1, b1;
if (hue < 60) {
r1 = chroma;
g1 = x;
b1 = 0;
} else if (hue < 120) {
r1 = x;
g1 = chroma;
b1 = 0;
} else if (hue < 180) {
r1 = 0;
g1 = chroma;
b1 = x;
} else if (hue < 240) {
r1 = 0;
g1 = x;
b1 = chroma;
} else if (hue < 300) {
r1 = x;
g1 = 0;
b1 = chroma;
} else {
r1 = chroma;
g1 = 0;
b1 = x;
}
r1 += m;
g1 += m;
b1 += m;
// convert to 0-255 range
int r2 = r1 * 255;
int g2 = g1 * 255;
int b2 = b1 * 255;
printf("ESL values: %.2f %.2f %.2f\n", hue_prime, chroma, m);
printf("RGB values: %d %d %d\n", r2, g2, b2);
return 0;
}
```
阅读全文