首页 > 后端开发 > C++ > 如何在 0-255 范围内有效地将 RGB 转换为 HSV,反之亦然?

如何在 0-255 范围内有效地将 RGB 转换为 HSV,反之亦然?

Susan Sarandon
发布: 2025-01-01 02:06:09
原创
779 人浏览过

How can I efficiently convert RGB to HSV and vice versa within the 0-255 range?

在 0-255 范围内将 RGB 转换为 HSV,反之亦然:实用代码解决方案

问题:

中在各种图像处理应用中,通常需要在 RGB 和 HSV 颜色空间之间转换颜色。为了确保无缝过渡,两个空间必须在相同的范围内工作,通常在 0 到 255 之间。

解决方案:

为了满足此要求,让我们探索一下经过验证的算法,可在指定范围内有效地在 RGB 和 HSV 之间转换颜色范围:

typedef struct {
    double r;
    double g;
    double b;
} rgb;

typedef struct {
    double h;
    double s;
    double v;
} hsv;
登录后复制
hsv rgb2hsv(rgb in)
{
    hsv         out;
    double      min, max, delta;

    min = in.r < in.g ? in.r : in.g;
    min = min  < in.b ? min  : in.b;

    max = in.r > in.g ? in.r : in.g;
    max = max  > in.b ? max  : in.b;

    out.v = max;
    delta = max - min;
    if (delta < 0.00001)
    {
        out.s = 0;
        out.h = 0; // undefined, maybe nan?
        return out;
    }
    if( max > 0.0 ) { // NOTE: if Max is == 0, this divide would cause a crash
        out.s = (delta / max);
    } else {
        // if max is 0, then r = g = b = 0              
        // s = 0, h is undefined
        out.s = 0.0;
        out.h = NAN;
        return out;
    }
    if( in.r >= max ) // > is bogus, just keeps compilor happy
        out.h = ( in.g - in.b ) / delta;        // between yellow & magenta
    else
    if( in.g >= max )
        out.h = 2.0 + ( in.b - in.r ) / delta;  // between cyan & yellow
    else
        out.h = 4.0 + ( in.r - in.g ) / delta;  // between magenta & cyan

    out.h *= 60.0;

    if( out.h < 0.0 )
        out.h += 360.0;

    return out;
}
登录后复制
rgb hsv2rgb(hsv in)
{
    double      hh, p, q, t, ff;
    long        i;
    rgb         out;

    if(in.s <= 0.0) {
        out.r = in.v;
        out.g = in.v;
        out.b = in.v;
        return out;
    }
    hh = in.h;
    if(hh >= 360.0) hh = 0.0;
    hh /= 60.0;
    i = (long)hh;
    ff = hh - i;
    p = in.v * (1.0 - in.s);
    q = in.v * (1.0 - (in.s * ff));
    t = in.v * (1.0 - (in.s * (1.0 - ff)));

    switch(i) {
    case 0:
        out.r = in.v;
        out.g = t;
        out.b = p;
        break;
    case 1:
        out.r = q;
        out.g = in.v;
        out.b = p;
        break;
    case 2:
        out.r = p;
        out.g = in.v;
        out.b = t;
        break;

    case 3:
        out.r = p;
        out.g = q;
        out.b = in.v;
        break;
    case 4:
        out.r = t;
        out.g = p;
        out.b = in.v;
        break;
    case 5:
    default:
        out.r = in.v;
        out.g = p;
        out.b = q;
        break;
    }
    return out;     
}
登录后复制

以上是如何在 0-255 范围内有效地将 RGB 转换为 HSV,反之亦然?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板