首頁 > 後端開發 > 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 之間。

解決方案:
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;     
}
登入後複製
為了滿足此要求,讓我們探索經過驗證的演算法,可在指定範圍內有效地在RGB 和HSV 之間轉換顏色範圍:

以上是如何在 0-255 範圍內有效地將 RGB 轉換為 HSV,反之亦然?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板