Skip to content

Instantly share code, notes, and snippets.

@Sorebit
Last active December 13, 2015 13:12
Show Gist options
  • Save Sorebit/fdd1c06bfa8e658c009f to your computer and use it in GitHub Desktop.
Save Sorebit/fdd1c06bfa8e658c009f to your computer and use it in GitHub Desktop.
#include <iostream>
#include <cmath>
// RGB color struct
struct Color { int r, g, b; };
// Round float to int
int round(float f) { return (f - (int)f >= 0.5) ? (f + 1) : f; }
// Returns an RGB color from an HSV one
Color hsv(int h, float s, float v)
{
// h: Hue [0, 360]
// s: Saturation [0, 1]
// v: Value [0, 1]
float r, g, b;
float c = v * s;
float x = c * (1.0 - std::fabs(std::fmod(h / 60.0, 2) - 1.0));
float m = v - c;
switch(h / 60)
{
case 0:
r = c + m;
g = x + m;
b = m;
break;
case 1:
r = x + m;
g = c + m;
b = m;
break;
case 2:
r = m;
g = c + m;
b = x + m;
break;
case 3:
r = m;
g = x + m;
b = c + m;
break;
case 4:
r = x + m;
b = m;
g = c + m;
break;
case 5:
r = c + m;
b = m;
g = x + m;
break;
default:
r = g = b = m;
}
return {round(r*255), round(g*255), round(b*255)};
}
int main()
{
int h;
float s, v;
std::cin >> h >> s >> v;
Color c = hsv(h, s, v);
std::cout << c.r << " " << c.g << " " << c.b << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment