Snippet: code to convert RGB to HSV and back again

I sketched this code together needing a quick way to convert from RGB to HSV and back again, then realized I didn’t need it. So I’m putting it here in the theory that this may be useful someday…

/*	RGBToHSV
 *
 *		Conver to HSV
 */

static void RGBToHSV(float r, float g, float b, float *h, float *s, float *v)
{
	float max = r;
	if (max < g) max = g;
	if (max  g) min = g;
	if (min > b) min = b;
	
	/*
	 *	Calculate h
	 */
	
	*h = 0;
	if (max == min) h = 0;
	else if (max == r) {
		*h = 60 * (g - b)/(max - min);
		if (*h = 360) *h -= 360;
	} else if (max == g) {
		*h = 60 * (b - r) / (max - min) + 120;
	} else if (max == b) {
		*h = 60 * (r - g) / (max - min) + 240;
	}

	if (max == 0) *s = 0;
	else *s = 1 - (min / max);

	*v = max;
}

/*	HSVToRGB
 *
 *		Convert to RGB
 */

static void HSVToRGB(float h, float s, float v, float *r, float *g, float *b)
{
	if (h  359) h = 359;
	if (s  1) s = 100;
	if (v  1) v = 100;

	float tmp = h/60.0;
	int hi = floor(tmp);
	float f = tmp - hi;
	float p = v * (1 - s);
	float q = v * (1 - f * s);
	float t = v * (1 - (1 - f) * s);
	
	switch (hi) {
		case 0:
			*r = v;
			*g = t;
			*b = p;
			break;
		case 1:
			*r = q;
			*g = v;
			*b = p;
			break;
		case 2:
			*r = p;
			*g = v;
			*b = t;
			break;
		case 3:
			*r = p;
			*g = q;
			*b = v;
			break;
		case 4:
			*r = t;
			*g = p;
			*b = v;
			break;
		case 5:
			*r = v;
			*g = p;
			*b = q;
			break;
	}
}

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s