(Zt) mutual conversion of RGB and HSV Color Space Modes

Source: Internet
Author: User
From: http://www.cnitblog.com/edaiqingwa/archive/2007/12/11/35643.html
When developing bitmap programs, you often need to convert the color of Bitmap between the RGB and HSV color spaces. The color conversion is implemented by C ++:

RGB color space to HSV color value:

Void rgb2hsv (float R, float g, float B, float & H, float & S, float & V)
{
// R, G, B values are from 0 to 1
// H = [0,360], S = [], V = []
// If S = 0, then H =-1 (undefined)

Float min, Max, Delta, TMP;
TMP = min (R, G );
Min = min (TMP, B );
TMP = max (R, G );
Max = max (TMP, B );
V = max; // v

Delta = max-min;

If (max! = 0)
S = delta/max; // s
Else
{
// R = G = B = 0 // s = 0, V is undefined
S = 0;
H = undefinedcolor;
Return;
}
If (r = max)
H = (G-B)/delta; // between yellow & Magenta
Else if (G = max)
H = 2 + (B-r)/delta; // between cyan & yellow
Else
H = 4 + (r-g)/delta; // between magenta & cyan

H * = 60; // degrees
If (H <0)
H ++ = 360;
}

Convert the HSV color space to the RGB color value:

Void HSV 2rgb (float H, float S, float V, float & R, float & G, float & B)
{
Int I;
Float F, p, q, T;

If (S = 0)
{
// Achromatic (Gray)
R = G = B = V;
Return;
}

H/= 60; // sector 0 to 5
I = floor (h );
F = h-I; // factorial part of H
P = V * (1-S );
Q = V * (1-S * F );
T = V * (1-S * (1-f ));

Switch (I)
{
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;
Default: // case 5:
R = V;
G = P;
B = Q;
Break;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.