C# setHue (or alternatively, convert HSL to RGB and set RGB) - c#

C# has a very convenient getHue method, but I can't find a setHue method. Is there one?
If not, I think the best way to define a color after changing the hue would be to convert the HSL value to RGB, and then set the RGB value. I know there are formulas on the internet for doing this, but how would I best go about performing this conversion from HSL to RGB using C#?
Thank You

To set the Hue you create a new Color, maybe from a given one by using GetHue and GetSaturation. See below for the getBrightness function!
I'm using this:
Color SetHue(Color oldColor)
{
var temp = new HSV();
temp.h = oldColor.GetHue();
temp.s = oldColor.GetSaturation();
temp.v = getBrightness(oldColor);
return ColorFromHSL(temp);
}
// A common triple float struct for both HSL & HSV
// Actually this should be immutable and have a nice constructor!!
public struct HSV { public float h; public float s; public float v;}
// the Color Converter
static public Color ColorFromHSL(HSV hsl)
{
if (hsl.s == 0)
{ int L = (int)hsl.v; return Color.FromArgb(255, L, L, L); }
double min, max, h;
h = hsl.h / 360d;
max = hsl.v < 0.5d ? hsl.v * (1 + hsl.s) : (hsl.v + hsl.s) - (hsl.v * hsl.s);
min = (hsl.v * 2d) - max;
Color c = Color.FromArgb(255, (int)(255 * RGBChannelFromHue(min, max,h + 1 / 3d)),
(int)(255 * RGBChannelFromHue(min, max,h)),
(int)(255 * RGBChannelFromHue(min, max,h - 1 / 3d)));
return c;
}
static double RGBChannelFromHue(double m1, double m2, double h)
{
h = (h + 1d) % 1d;
if (h < 0) h += 1;
if (h * 6 < 1) return m1 + (m2 - m1) * 6 * h;
else if (h * 2 < 1) return m2;
else if (h * 3 < 2) return m1 + (m2 - m1) * 6 * (2d / 3d - h);
else return m1;
}
Do not use the built-in GetBrightness method! It returns the same value (0.5f) for red, magenta, cyan, blue and yellow (!). This is better:
// color brightness as perceived:
float getBrightness(Color c)
{ return (c.R * 0.299f + c.G * 0.587f + c.B *0.114f) / 256f; }

System.Drawing.Color is a value type, which are almost always made immutable, especially in frameworks. That's why you can't setHue on it, you can only construct a new value type with fields you need.
So, if you have a function that will give you RGB values for your HSB values, you can do it like this
Color oldColor = ...;
int red, green, blue;
FromHSB(oldColor.GetHue(), oldColor.GetSaturation(), oldColor.GetBrightness(), out red, out green out blue);
Color newColor = Color.FromArgb(oldColor.A, red, green, blue);
where FromHSB looks like this
void FromHSB(float hue, float saturation, float brightness, out int red, out int green, out int blue)
{
// ...
}

Related

How to change color hue in XNA?

I have a color of class Microsoft.Xna.Framework.Color. How can I change its hue (or get a new color with slightly different hue). Should I convert it to System.Drawing.Color, then somehow change it and convert back? I can't find any useful information on this anywhere.
EDIT
Example:
I have red color R:255, G:0, B:0. Now I want to get slightly more orange color. Then if I get this color and transform it again I'll get even more orange color, then after some transformations I'll go to yellow, green etc. I don't know exact values of ARGB of each color and I don't need them. I just need to change hue of a color by some factor (for example 10 degrees).
You should use the A R G B properties and change the values to get different nyansers.
For example:
Color color = new Color(0,0,0);
//Then you can change the argb properties:
color.A = 10;
color.R = 15;
color.G = 9;
color.B = 25;
If I understand you need something like this:
public static class Utilities
{
public static void Increase(this Color color, int value)
{
if(color.R >= color.G && color.R >= color.B)
color.R += value;
else if(color.G >= color.R && color.G >= color.B)
color.G += value;
else
color.B += value;
}
public static void Decrease(this Color color, int value)
{
if(color.R <= color.G && color.R <= color.B)
color.R -= value;
else if(color.G <= color.R && color.G <= color.B)
color.G -= value;
else
color.B -= value;
}
}
Then:
Color myColor = new Color(10,0,0);
myColor.Increase(10);
//or
myColor.Decrease(10);
according to this documentation, you can pass whatever RGB(A) values you want into the XNA color class constructor. You can also use the R, B, and G properties to change them afterwards
example:
Color myColor = new Color(150, 100, 100);
myColor.R = 200
that example will change a red to a slightly deeper red.
An example of making a color go from Red to orange to yellow to green would be
Color myColor = new Color(255, 0, 0);
for(int i=0; i<255; i++)
{
myColor.R--;
myColor.G++
}
Red and Green make yellow, so higher numbers of red will make it redder, higher numbers of green will make it greener. same of both numbers make it redder.
You can change color incrementally in other ways too, so long as you know how the primary colors of light work.
You're never ever going to find a function called Color.MakeRedder() or Color.MakeGreener() It will always focus on some sort of mathmatical representation of the color, (RBG is most common but there are other representations)
If you want to convert Hue to RBG Here is a guide on how to do it
What would probably be easiest is to keep track of a System.Drawing.Color class as your base color class, and modify your XNA Color Class based on your System.Drawing.Color class accordingly.
If you want to get really adventurous, you can see if it is possible to make a class that extends(inherits from) Microsoft.Xna.Framework.Color, override the R, G, and B properties, so that they are based off of an underlying System.Drawing.Color object
I did some research and found this post which has C++ code:
http://www.cs.rit.edu/~ncs/color/t_convert.html
I've modified the code to be C#, to have an IncreaseHueBy method, and to fix a few bugs:
public static void IncreaseHueBy(ref Color color, float value, out float hue)
{
float h, s, v;
RgbToHsv(color.R, color.G, color.B, out h, out s, out v);
h += value;
float r, g, b;
HsvToRgb(h, s, v, out r, out g, out b);
color.R = (byte)(r);
color.G = (byte)(g);
color.B = (byte)(b);
hue = h;
}
static void RgbToHsv(float r, float g, float b, out float h, out float s, out float v)
{
float min, max, delta;
min = System.Math.Min(System.Math.Min(r, g), b);
max = System.Math.Max(System.Math.Max(r, g), b);
v = max; // v
delta = max - min;
if (max != 0)
{
s = delta / max; // s
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;
}
else
{
// r = g = b = 0 // s = 0, v is undefined
s = 0;
h = -1;
}
}
static void HsvToRgb(float h, float s, float v, out float r, out float g, out float b)
{
// Keeps h from going over 360
h = h - ((int)(h / 360) * 360);
int i;
float f, p, q, t;
if (s == 0)
{
// achromatic (grey)
r = g = b = v;
return;
}
h /= 60; // sector 0 to 5
i = (int)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;
}
}
I tested it by using a value of 1 to increase the hue by 1 every frame and it worked fairly well. Notice there may be some rounding errors.

Splitting the color circle into sections

How I can programmatically split the color circle into sections, and how I can get all RGB color in this sections ?
I want fce which returns me the color section by input parament in RGB color.
int getColorSection(RGB color);
I don't know if i understood correctly the question, but i think you are asking if a color is more green, more blue or blue red?
This will give you informations on in what section (Red, Green or Blue) it is.
For doing that, without keeping in account human perception of colors, you can do:
public enum ColorSection
{
Red,
Green,
Blue
}
public ColorSection GetColorSection(int rgb)
{
int r = rgb & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = (rgb >> 16) & 0xFF;
return (r > g && r > b) ? ColorSection.Red : ((g > b) ? ColorSection.Green : ColorSection.Blue);
}
Of course this don't work very well if you have colors with two equal values, if you have red = green, it returns red.
If you have white it returns red, if you have black, it returns blue.
If you need something more fancy, probably as you are asking, then you need to use neirest neighbour approximation and polar coordinates.
You can compute the angle using, as pointed out, the Hue.
From the angle then you can just convert it to an integer.
To compute the hue:
public static double GetHue(int rgb)
{
double result = 0.0;
int r = rgb & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = (rgb >> 16) & 0xFF;
if (r != g && g != b)
{
double red = r / 255.0;
double green = g / 255.0;
double blue = b / 255.0;
double max = Math.Max(Math.Max(red, green), blue);
double min = Math.Min(Math.Min(red, green), blue);
double delta = max - min;
if (delta != 0)
{
if (red == max)
result = (green - blue) / delta;
else if (green == max)
result = 2 + ((blue - red) / delta);
else if (blue == max)
result = 4 + ((red - green) / delta);
result *= 60.0;
if (result < 0)
result += 360.0;
}
}
return result;
}
It returns the angle, in degrees, from 0 to 360, of where are you in the color wheel.
You can compute than the section using neirest neighbour.
For example:
const int NumberOfSections = 10;
int section = (int)(GetHue() * NumberOfSections / 360.0);
Your wheel however seems rotated in respect to the C# color wheel.
You probably need to substract a constant angle that is the exact difference.
If i'm not wrong, the difference is 180°.
public static double GetMyHue(int rgb)
{
return (GetHue(rgb) + 180.0) % 360.0;
}
Use the HSL color space. The H is the hue, the angle of the color on the color circle. You can get it directly from the System.Drawing.Color.GetHue() method.

Converting RGB to HSB Colors

I am trying to convert a HSB Color to RGB. The way I am doing that is
System.Windows.Media.Color winColor = value;
System.Drawing.Color drawColor = System.Drawing.Color.FromArgb(winColor.R, winColor.G, winColor.B);
Hue = (byte)(drawColor.GetHue()*255);
Saturation = (byte)(drawColor.GetSaturation()*255);
Luminosity = (byte)(drawColor.GetBrightness()*255);
I find that when I have FF0000, it will be converted to H = 0, S = 255, L = 127 which converts to RGB FF0E0E. I think Luminosity should be 120? Or am I getting the whole HSB thing wrong? When I look at the color picker in Photoshop, Hue is 0-360 degrees, Saturation, Luminosity is 0-100%. I am having HSB values ranging from 0 - 255, am I doing it wrong?
Maybe you already look into this wikipedia article, but to make it clear.
There is a difference between HSL and HSB (aka HSV).
So you can't take the (B)rightness from the color class and use it like a (L)uminosity.
To get back from the Color class provided values GetHue(), GetSaturation() and GetBrightness() to a normal color you should give this extension method a chance.
/// <summary>
/// Creates a Color from alpha, hue, saturation and brightness.
/// </summary>
/// <param name="alpha">The alpha channel value.</param>
/// <param name="hue">The hue value.</param>
/// <param name="saturation">The saturation value.</param>
/// <param name="brightness">The brightness value.</param>
/// <returns>A Color with the given values.</returns>
public static Color FromAhsb(int alpha, float hue, float saturation, float brightness)
{
if (0 > alpha
|| 255 < alpha)
{
throw new ArgumentOutOfRangeException(
"alpha",
alpha,
"Value must be within a range of 0 - 255.");
}
if (0f > hue
|| 360f < hue)
{
throw new ArgumentOutOfRangeException(
"hue",
hue,
"Value must be within a range of 0 - 360.");
}
if (0f > saturation
|| 1f < saturation)
{
throw new ArgumentOutOfRangeException(
"saturation",
saturation,
"Value must be within a range of 0 - 1.");
}
if (0f > brightness
|| 1f < brightness)
{
throw new ArgumentOutOfRangeException(
"brightness",
brightness,
"Value must be within a range of 0 - 1.");
}
if (0 == saturation)
{
return Color.FromArgb(
alpha,
Convert.ToInt32(brightness * 255),
Convert.ToInt32(brightness * 255),
Convert.ToInt32(brightness * 255));
}
float fMax, fMid, fMin;
int iSextant, iMax, iMid, iMin;
if (0.5 < brightness)
{
fMax = brightness - (brightness * saturation) + saturation;
fMin = brightness + (brightness * saturation) - saturation;
}
else
{
fMax = brightness + (brightness * saturation);
fMin = brightness - (brightness * saturation);
}
iSextant = (int)Math.Floor(hue / 60f);
if (300f <= hue)
{
hue -= 360f;
}
hue /= 60f;
hue -= 2f * (float)Math.Floor(((iSextant + 1f) % 6f) / 2f);
if (0 == iSextant % 2)
{
fMid = (hue * (fMax - fMin)) + fMin;
}
else
{
fMid = fMin - (hue * (fMax - fMin));
}
iMax = Convert.ToInt32(fMax * 255);
iMid = Convert.ToInt32(fMid * 255);
iMin = Convert.ToInt32(fMin * 255);
switch (iSextant)
{
case 1:
return Color.FromArgb(alpha, iMid, iMax, iMin);
case 2:
return Color.FromArgb(alpha, iMin, iMax, iMid);
case 3:
return Color.FromArgb(alpha, iMin, iMid, iMax);
case 4:
return Color.FromArgb(alpha, iMid, iMin, iMax);
case 5:
return Color.FromArgb(alpha, iMax, iMin, iMid);
default:
return Color.FromArgb(alpha, iMax, iMid, iMin);
}
}
Update
So just to make things clear. My code above and the three methods within the Color class mentioned above are using the HSB (aka HSV) color model, but Photoshop uses the HSL color model.
In your comment you wrote that the parameters Hue = 0, Saturation = 1 and Brightness = 1 give you with the code above a red color and white in Photoshop. When you take a closer look at the differences of these modes this makes absolutely sense:
The HSL cylinder
(source: wikimedia.org)
In both models the hue acts as the same by using color Red as start and end point (zero and 360 degree).
By just looking at the hue you've got a red color.
The saturation defines how opaque the color is or how much the portion of a whitescale is.
So by setting it to one you say you want a full shiny red color.
The lighting now defines how much is the black and white part within your color. By setting it to zero you got black, one means white and 0.5 means perfect weighting.
So by setting it to one you say you want it as bright as possible which result in a white color.
The HSB cylinder
(source: wikimedia.org)
In both models the hue acts as the same by using color Red as start and end point (zero and 360 degree).
By just looking at the hue you've got a red color.
The saturation defines how opaque the color is or how much the portion of a whitescale is.
So by setting it to one you say you want a full shiny red color.
The brightness (or value) now defines how much is the black part within the color (not the white part).
So by setting it to one you say you want it full colored leading to a full shiny red color.
As you can see, Photoshop and the .Net framework (including my extension function) are using different coloring models. So you should check if you find somewhere an implementation of the other coloring model, a transformation or something else that gives you the results you need.
This works...modified from Java source code. The other answer is still HSL, This really is HSB to RGB (actually it's HSB/HSV to System.Windows.Media.Color as my return type)
public static Color HSBtoRGB(float hue, float saturation, float brightness)
{
int r = 0, g = 0, b = 0;
if (saturation == 0)
{
r = g = b = (int)(brightness * 255.0f + 0.5f);
}
else
{
float h = (hue - (float)Math.Floor(hue)) * 6.0f;
float f = h - (float)Math.Floor(h);
float p = brightness * (1.0f - saturation);
float q = brightness * (1.0f - saturation * f);
float t = brightness * (1.0f - (saturation * (1.0f - f)));
switch ((int)h)
{
case 0:
r = (int)(brightness * 255.0f + 0.5f);
g = (int)(t * 255.0f + 0.5f);
b = (int)(p * 255.0f + 0.5f);
break;
case 1:
r = (int)(q * 255.0f + 0.5f);
g = (int)(brightness * 255.0f + 0.5f);
b = (int)(p * 255.0f + 0.5f);
break;
case 2:
r = (int)(p * 255.0f + 0.5f);
g = (int)(brightness * 255.0f + 0.5f);
b = (int)(t * 255.0f + 0.5f);
break;
case 3:
r = (int)(p * 255.0f + 0.5f);
g = (int)(q * 255.0f + 0.5f);
b = (int)(brightness * 255.0f + 0.5f);
break;
case 4:
r = (int)(t * 255.0f + 0.5f);
g = (int)(p * 255.0f + 0.5f);
b = (int)(brightness * 255.0f + 0.5f);
break;
case 5:
r = (int)(brightness * 255.0f + 0.5f);
g = (int)(p * 255.0f + 0.5f);
b = (int)(q * 255.0f + 0.5f);
break;
}
}
return Color.FromArgb(Convert.ToByte(255), Convert.ToByte(r), Convert.ToByte(g), Convert.ToByte(b));
}
Since the other answers don't seem to work for me (and I didn't have the patience to see what's going on), I'm sharing my code for HSV->RGB conversion. It's based on the section "Alternate HSV conversion" on Wikipedia and is quite compact.
public static Color FromAhsv(byte alpha, float hue, float saturation, float value)
{
if (hue < 0f || hue > 360f)
throw new ArgumentOutOfRangeException(nameof(hue), hue, "Hue must be in the range [0,360]");
if (saturation < 0f || saturation > 1f)
throw new ArgumentOutOfRangeException(nameof(saturation), saturation, "Saturation must be in the range [0,1]");
if (value < 0f || value > 1f)
throw new ArgumentOutOfRangeException(nameof(value), value, "Value must be in the range [0,1]");
int Component(int n)
{
var k = (n + hue / 60f) % 6;
var c = value - value * saturation * Math.Max(Math.Min(Math.Min(k, 4 - k), 1), 0);
var b = (int)Math.Round(c * 255);
return b < 0 ? 0 : b > 255 ? 255 : b;
}
return Color.FromArgb(alpha, Component(5), Component(3), Component(1));
}
You can use ColorHelper library for this:
using ColorHelper;
RGB rgb = new RGB(20, 20, 20);
HSV hsv = ColorConverter.RgbToHsv(rgb);
Links:
Github
Nuget

C#: Create a lighter/darker color based on a system color [duplicate]

This question already has answers here:
How do I adjust the brightness of a color?
(7 answers)
Closed 1 year ago.
Duplicate
How do I adjust the brightness of a color?
How do I determine darker or lighter color variant of a given color?
Programmatically Lighten a Color
Say I have
var c = Color.Red;
Now I want to create a new Color that is lighter or darker than that color. How can I do that without too much hassle?
ControlPaint.Light .Dark .DarkDark, etc.
Color lightRed = ControlPaint.Light( Color.Red );
I recently blogged about this. The main idea is to apply a given correction factor to each of the color components. The following static method modifies the brightness of a given color with a specified correction factor and produces a darker or a lighter variant of that color:
/// <summary>
/// Creates color with corrected brightness.
/// </summary>
/// <param name="color">Color to correct.</param>
/// <param name="correctionFactor">The brightness correction factor. Must be between -1 and 1.
/// Negative values produce darker colors.</param>
/// <returns>
/// Corrected <see cref="Color"/> structure.
/// </returns>
public static Color ChangeColorBrightness(Color color, float correctionFactor)
{
float red = (float)color.R;
float green = (float)color.G;
float blue = (float)color.B;
if (correctionFactor < 0)
{
correctionFactor = 1 + correctionFactor;
red *= correctionFactor;
green *= correctionFactor;
blue *= correctionFactor;
}
else
{
red = (255 - red) * correctionFactor + red;
green = (255 - green) * correctionFactor + green;
blue = (255 - blue) * correctionFactor + blue;
}
return Color.FromArgb(color.A, (int)red, (int)green, (int)blue);
}
You can also do this using a Lerp function. There's one in XNA, but it's easy to write yourself.
See my answer to this similar question for a C# implementation.
The function lets you do this:
// make red 50% lighter:
Color.Red.Lerp( Color.White, 0.5 );
// make red 75% darker:
Color.Red.Lerp( Color.Black, 0.75 );
// make white 10% bluer:
Color.White.Lerp( Color.Blue, 0.1 );
Most of these methods do darken the color but they adjust the hue way to much so the result doesn't look very good. The best answer is to use Rich Newman's HSLColor class and adjust the luminosity.
public Color Darken(Color color, double darkenAmount) {
HSLColor hslColor = new HSLColor(color);
hslColor.Luminosity *= darkenAmount; // 0 to 1
return hslColor;
}
Taking the core method of #Pavel's answer I prepared the following two little extension methods for a more intuitive (at least for me) signature.
public static Color LightenBy(this Color color, int percent)
{
return ChangeColorBrightness(color, percent/100.0);
}
public static Color DarkenBy(this Color color, int percent)
{
return ChangeColorBrightness(color, -1 * percent / 100.0);
}
Here's some javascript code I use for lightening/darkening a given colour. You could use it as a base for an equivalent C# function
It works by calculating a distance from pure white of each of the RGB components and then adjusts this distance by the provided factor. The new distance is used to calculate the new colour. A factor of between 0 and 1 darkens, a factor higher than 1 lightens
function Darken( hexColor, factor )
{
if ( factor < 0 ) factor = 0;
var c = hexColor;
if ( c.substr(0,1) == "#" )
{
c = c.substring(1);
}
if ( c.length == 3 || c.length == 6 )
{
var i = c.length / 3;
var f; // the relative distance from white
var r = parseInt( c.substr(0, i ), 16 );
f = ( factor * r / (256-r) );
r = Math.floor((256 * f) / (f+1));
r = r.toString(16);
if ( r.length == 1 ) r = "0" + r;
var g = parseInt( c.substr(i, i), 16);
f = ( factor * g / (256-g) );
g = Math.floor((256 * f) / (f+1));
g = g.toString(16);
if ( g.length == 1 ) g = "0" + g;
var b = parseInt( c.substr( 2*i, i),16 );
f = ( factor * b / (256-b) );
b = Math.floor((256 * f) / (f+1));
b = b.toString(16);
if ( b.length == 1 ) b = "0" + b;
c = r+g+b;
}
return "#" + c;
}
You can also simply work on the RGB percentage to get it lighter or darker as you want, Here is an example for how to make a color darker x% than it is:
//_correctionfactory in percentage, e.g 50 = make it darker 50%
private Color DarkerColor(Color color, float correctionfactory = 50f)
{
const float hundredpercent = 100f;
return Color.FromArgb((int)(((float)color.R / hundredpercent) * correctionfactory),
(int)(((float)color.G / hundredpercent) * correctionfactory), (int)(((float)color.B / hundredpercent) * correctionfactory));
}
One more thing we can also reverse the process to be lighter instead, Only we getting the result of 255 - RGB and then multiply it by the percentage we want like the following example:
private Color LighterColor(Color color, float correctionfactory = 50f)
{
correctionfactory = correctionfactory / 100f;
const float rgb255 = 255f;
return Color.FromArgb((int)((float)color.R + ((rgb255 - (float)color.R) * correctionfactory)), (int)((float)color.G + ((rgb255 - (float)color.G) * correctionfactory)), (int)((float)color.B + ((rgb255 - (float)color.B) * correctionfactory))
);
}
Hope that helps.
I made a site that does this colorglower.com You can check it out to see a demo.
Here's the javascript code i used.
function lighten(color) {
// convert to decimal and change luminosity
var luminosity = 0.01
var computedColors = new Array();
var newColor = "#",
c, i, n, black = 0,
white = 255;
for (n = 0; n < 10; n++) {
for (i = 0; i < 3; i++) {
c = parseInt(color.substr(i * 2, 2), 16);
c = Math.round(Math.min(Math.max(black, c + (luminosity * white)), white)).toString(16);
newColor += ("00" + c).substr(c.length);
}
computedColors[n] = newColor;
var arrayUnique = checkIfArrayIsUnique(computedColors);
if (arrayUnique == false) {
computedColors.pop();
break;
}
computedColors[n] = newColor;
newColor = "#";
luminosity += calcPercentage();
}
return computedColors;
}
What this code does is it receives a hex color and then it outputs 10 lightest color versions of it and puts in in the array. You can change the luminosity to whatever you like to adjust the shade percentage. To darken the colors you just need to change:
luminosity -= calcPercentage();
Using HSI converter library(search google). And then, adjust I channel for lighter/darker color.
I changed Pavel Vladov function to modify even RGB component, to get shades on any combination of R/G/B directions:
Public Function ChangeColorShades(color As Color, correctionFactor As Single, bR As Boolean, bG As Boolean, bB As Boolean) As Color
Dim red As Single = CSng(color.R)
Dim green As Single = CSng(color.G)
Dim blue As Single = CSng(color.B)
If (correctionFactor < 0) Then
correctionFactor = 1 + correctionFactor
If bR Then
red *= correctionFactor
End If
If bG Then
green *= correctionFactor
End If
If bB Then
blue *= correctionFactor
End If
Else
If bR Then
red = (255 - red) * correctionFactor + red
End If
If bG Then
green = (255 - green) * correctionFactor + green
End If
If bB Then
blue = (255 - blue) * correctionFactor + blue
End If
End If
Return color.FromArgb(color.A, CInt(red), CInt(green), CInt(blue))
End Function

How to Convert RGB Color to HSV?

How can I convert a RGB Color to HSV using C#?
I've searched for a fast method without using any external library.
Note that Color.GetSaturation() and Color.GetBrightness() return HSL values, not HSV.
The following code demonstrates the difference.
Color original = Color.FromArgb(50, 120, 200);
// original = {Name=ff3278c8, ARGB=(255, 50, 120, 200)}
double hue;
double saturation;
double value;
ColorToHSV(original, out hue, out saturation, out value);
// hue = 212.0
// saturation = 0.75
// value = 0.78431372549019607
Color copy = ColorFromHSV(hue, saturation, value);
// copy = {Name=ff3278c8, ARGB=(255, 50, 120, 200)}
// Compare that to the HSL values that the .NET framework provides:
original.GetHue(); // 212.0
original.GetSaturation(); // 0.6
original.GetBrightness(); // 0.490196079
The following C# code is what you want. It converts between RGB and HSV using the algorithms described on Wikipedia. The ranges are 0 - 360 for hue, and 0 - 1 for saturation or value.
public static void ColorToHSV(Color color, out double hue, out double saturation, out double value)
{
int max = Math.Max(color.R, Math.Max(color.G, color.B));
int min = Math.Min(color.R, Math.Min(color.G, color.B));
hue = color.GetHue();
saturation = (max == 0) ? 0 : 1d - (1d * min / max);
value = max / 255d;
}
public static Color ColorFromHSV(double hue, double saturation, double value)
{
int hi = Convert.ToInt32(Math.Floor(hue / 60)) % 6;
double f = hue / 60 - Math.Floor(hue / 60);
value = value * 255;
int v = Convert.ToInt32(value);
int p = Convert.ToInt32(value * (1 - saturation));
int q = Convert.ToInt32(value * (1 - f * saturation));
int t = Convert.ToInt32(value * (1 - (1 - f) * saturation));
if (hi == 0)
return Color.FromArgb(255, v, t, p);
else if (hi == 1)
return Color.FromArgb(255, q, v, p);
else if (hi == 2)
return Color.FromArgb(255, p, v, t);
else if (hi == 3)
return Color.FromArgb(255, p, q, v);
else if (hi == 4)
return Color.FromArgb(255, t, p, v);
else
return Color.FromArgb(255, v, p, q);
}
Have you considered simply using System.Drawing namespace? For example:
System.Drawing.Color color = System.Drawing.Color.FromArgb(red, green, blue);
float hue = color.GetHue();
float saturation = color.GetSaturation();
float lightness = color.GetBrightness();
Note that it's not exactly what you've asked for (see differences between HSL and HSV and the Color class does not have a conversion back from HSL/HSV but the latter is reasonably easy to add.
The EasyRGB has many color space conversions. Here is the code for the RGB->HSV conversion.
There's a C implementation here:
http://www.cs.rit.edu/~ncs/color/t_convert.html
Should be very straightforward to convert to C#, as almost no functions are called - just calculations.
found via Google
This is the VB.net version which works fine for me ported from the C code in BlaM's post.
There's a C implementation here:
http://www.cs.rit.edu/~ncs/color/t_convert.html
Should be very straightforward to convert to C#, as almost no functions are called - just > calculations.
Public Sub HSVtoRGB(ByRef r As Double, ByRef g As Double, ByRef b As Double, ByVal h As Double, ByVal s As Double, ByVal v As Double)
Dim i As Integer
Dim f, p, q, t As Double
If (s = 0) Then
' achromatic (grey)
r = v
g = v
b = v
Exit Sub
End If
h /= 60 'sector 0 to 5
i = Math.Floor(h)
f = h - i 'factorial part of h
p = v * (1 - s)
q = v * (1 - s * f)
t = v * (1 - s * (1 - f))
Select Case (i)
Case 0
r = v
g = t
b = p
Exit Select
Case 1
r = q
g = v
b = p
Exit Select
Case 2
r = p
g = v
b = t
Exit Select
Case 3
r = p
g = q
b = v
Exit Select
Case 4
r = t
g = p
b = v
Exit Select
Case Else 'case 5:
r = v
g = p
b = q
Exit Select
End Select
End Sub
I've ended up here by having the same need.
Bellow I'm sharing the best and simpler solution I could find so far.
This is a modified answer from Greg's (found here); but with a humbler and understandable code.
For those who are learning I've added a few references that are worth checking for the sake of understanding.
References
"Lukas Stratmann" HSV Model Tool (Incl. Other Model Systems: CMY / CMYK / HSL)
"The HSV Color Model in Graphic Design"
"Formula to Determine Perceived Brightness of RGB Color"
Fastest Formula to Get Hue from RGB
"Color Conversion Algorithms"
"Program to Change RGB color model to HSV color model"
"RGB to HSV Color Conversion Algorithm"
"RGB to HSV Color Space Conversion (C)"
"How to Convert RGB Color to HSV"
Code
/// <summary> Convert RGB Color to HSV. </summary>
/// <param name="color"></param>
/// <returns> A double[] Containing HSV Color Values. </returns>
public double[] rgbToHSV(Color color)
{
double[] output = new double[3];
double hue, saturation, value;
int max = Math.Max(color.R, Math.Max(color.G, color.B));
int min = Math.Min(color.R, Math.Min(color.G, color.B));
hue = color.GetHue();
saturation = (max == 0) ? 0 : 1d - (1d * min / max);
value = max / 255d;
output[0] = hue;
output[1] = saturation;
output[2] = value;
return output;
}
FIRST: make sure you have a color as a bitmap, like this:
Bitmap bmp = (Bitmap)pictureBox1.Image.Clone();
paintcolor = bmp.GetPixel(e.X, e.Y);
(e is from the event handler wich picked my color!)
What I did when I had this problem a whilke ago, I first got the rgba (red, green, blue and alpha) values.
Next I created 3 floats: float hue, float saturation, float brightness. Then you simply do:
hue = yourcolor.Gethue;
saturation = yourcolor.GetSaturation;
brightness = yourcolor.GetBrightness;
The whole lot looks like this:
Bitmap bmp = (Bitmap)pictureBox1.Image.Clone();
paintcolor = bmp.GetPixel(e.X, e.Y);
float hue;
float saturation;
float brightness;
hue = paintcolor.GetHue();
saturation = paintcolor.GetSaturation();
brightness = paintcolor.GetBrightness();
If you now want to display them in a label, just do:
yourlabelname.Text = hue.ToString;
yourlabelname.Text = saturation.ToString;
yourlabelname.Text = brightness.ToString;
Here you go, you now have RGB Values into HSV values :)
Hope this helps

Categories