HSV与RGB之间相互转换

代码来自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);
}





转载于:https://my.oschina.net/kevinvane/blog/484817

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值