码迷,mamicode.com
首页 > 其他好文 > 详细

HSV与RGB之间相互转换

时间:2015-07-28 19:02:18      阅读:623      评论:0      收藏:0      [点我收藏+]

标签:

代码来自http://www.cocoabuilder.com/archive/cocoa/198570-here-is-code-to-convert-rgb-hsb.html

C语言,可在Object-C中调用

#define UNDEFINED 0

typedef struct {float r, g, b;} RGBType;
typedef struct {float h, s, v;} HSVType;

// Theoretically, hue 0 (pure red) is identical to hue 6 in these transforms. Pure
// red always maps to 6 in this implementation. Therefore UNDEFINED can be
// defined as 0 in situations where only unsigned numbers are desired.
RGBType RGBTypeMake(float r, float g, float b);
HSVType HSVTypeMake(float h, float s, float v);

HSVType RGB_to_HSV( RGBType RGB );
RGBType HSV_to_RGB( HSVType HSV );





#include <math.h>
#include "HSV.h"

inline RGBType RGBTypeMake(float r, float g, float b)
{
	RGBType rgb = {r, g, b};
	return rgb;
}

inline HSVType HSVTypeMake(float h, float s, float v)
{
	HSVType hsv = {h, s, v};
	return hsv;
}

HSVType RGB_to_HSV( RGBType RGB )
{
    // RGB are each on [0, 1]. S and V are returned on [0, 1] and H is
    // returned on [0, 1]. Exception: H is returned UNDEFINED if S==0.
    float R = RGB.r, G = RGB.g, B = RGB.b, v, x, f;
    int i;
	
    x = fminf(R, G);
    x = fminf(x, B);
	
    v = fmaxf(R, G);
    v = fmaxf(v, B);
	
    if(v == x) 
		return HSVTypeMake(UNDEFINED, 0, v);
	
    f = (R == x) ? G - B : ((G == x) ? B - R : R - G);
    i = (R == x) ? 3 : ((G == x) ? 5 : 1);
	
    return HSVTypeMake(((i - f /(v - x))/6), (v - x)/v, v);
}

RGBType HSV_to_RGB( HSVType HSV )
{
    // H is given on [0, 1] or UNDEFINED. S and V are given on [0, 1].
    // RGB are each returned on [0, 1].
    float h = HSV.h * 6, s = HSV.s, v = HSV.v, m, n, f;
    int i;

    if (h == 0) h=.01;
    if(h == UNDEFINED) 
		return RGBTypeMake(v, v, v);
    i = floorf(h);
    f = h - i;
    if(!(i & 1)) f = 1 - f; // if i is even
    m = v * (1 - s);
    n = v * (1 - s * f);
    switch (i)
	{
        case 6:
        case 0: return RGBTypeMake(v, n, m);
        case 1: return RGBTypeMake(n, v, m);
        case 2: return RGBTypeMake(m, v, n);
        case 3: return RGBTypeMake(m, n, v);
        case 4: return RGBTypeMake(n, m, v);
        case 5: return RGBTypeMake(v, m, n);
	}
    return RGBTypeMake(0, 0, 0);
}





HSV与RGB之间相互转换

标签:

原文地址:http://my.oschina.net/kevinvane/blog/484817

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!