Skip to content

Instantly share code, notes, and snippets.

@rzhukov
Created February 21, 2014 06:05
Show Gist options
  • Save rzhukov/9129585 to your computer and use it in GitHub Desktop.
Save rzhukov/9129585 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);
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));
}
@KernelA
Copy link

KernelA commented May 4, 2019

HSI to RGB conversion works incorrectly for black, white and grayscale. For example, black color is (1, 1, 1). In HSI is (-nan, 0, 1). Inverse conversion HSI to RGB gives (-nan, 0, 1). Need to check h value on NaN.

https://gist.github.com/KernelA/b462a49200c26028344783edaa639b2d

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment