Skip to content

Instantly share code, notes, and snippets.

@rzhukov
Created February 21, 2014 06:05

Revisions

  1. rzhukov created this gist Feb 21, 2014.
    39 changes: 39 additions & 0 deletions rgb_hsi.h
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,39 @@
    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));
    }