Skip to content

Instantly share code, notes, and snippets.

@KernelA
Forked from rzhukov/rgb_hsi.h
Last active November 11, 2020 10:35
Show Gist options
  • Save KernelA/b462a49200c26028344783edaa639b2d to your computer and use it in GitHub Desktop.
Save KernelA/b462a49200c26028344783edaa639b2d to your computer and use it in GitHub Desktop.
RGB to HSI and HSI to RGB color space conversion
inline void HSI2RGB(double h, double s, double i, double* r, double* g, double* b)
{
double x = i * (1 - s);
// For black, white and grayscale h is NaN. Conversion works incorrectly.
if(std::isnan(h))
{
*r = i;
*g = i;
*b = i;
}
else if(h < 2 * M_PI / 3)
{
double y = i * (1 + (s * cos(h)) / (cos(M_PI / 3 - h)));
double z = 3 * i - (x + y);
*b = x; *r = y; *g = z;
}
else if(h < 4 * M_PI / 3)
{
double y = i * (1 + (s * cos(h - 2 * M_PI / 3)) / (cos(M_PI / 3 - (h - 2 * M_PI / 3))));
double z = 3 * i - (x + y);
*r = x; *g = y; *b = z;
}
else
{
double y = i * (1 + (s * cos(h - 4 * M_PI / 3)) / (cos(M_PI / 3 - (h - 4 * M_PI / 3))));
double z = 3 * i - (x + y);
*r = z; *g = x; *b = y;
}
}
inline void RGB2HSI(double r, double g, double b, double* h, double* s, double* i)
{
*i = (r + g + b) / 3.0;
double rn = r / (r + g + b);
double gn = g / (r + g + b);
double bn = b / (r + g + b);
*h = acos((0.5 * ((rn - gn) + (rn - bn))) / (sqrt((rn - gn) * (rn - gn) + (rn - bn) * (gn - bn))));
if(b > g)
{
*h = 2 * M_PI - *h;
}
*s = 1 - 3 * min(rn, min(gn, bn));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment