public int DeltaSa(Dye other) { var myS = Color.GetSaturation(); var otherS = other.Color.GetSaturation(); return((int)(100 * (myS < otherS ? 1.0 + otherS - myS : 1.0 - (myS - otherS)) + 0.5)); // ImageMagick interprets 100 as unchanged (100%), 0 is grayscale, 200 is very colorful (cartoonish) }
private static String FormatColor(String format, Color arg) { if (String.IsNullOrWhiteSpace(format)) { return arg.ToString(); } var numberFormatInfo = new NumberFormatInfo { NumberDecimalDigits = 1, PercentDecimalDigits = 0, PercentNegativePattern = 1, PercentPositivePattern = 1 }; switch (format) { case "hex": { return String.Format(numberFormatInfo, "#{0:x2}{1:x2}{2:x2}", arg.R, arg.G, arg.B); } case "HEX": { return String.Format(numberFormatInfo, "#{0:X2}{1:X2}{2:X2}", arg.R, arg.G, arg.B); } case "rgb": { return String.Format(numberFormatInfo, "rgb({0}, {1}, {2})", arg.R, arg.G, arg.B); } case "rgb%": { return String.Format(numberFormatInfo, "rgb({0:P}, {1:P}, {2:P})", arg.R / 255d, arg.G / 255d, arg.B / 255d); } case "rgba": { return String.Format(numberFormatInfo, "rgba({0}, {1}, {2}, {3:0.#})", arg.R, arg.G, arg.B, arg.A / 255d); } case "rgba%": { return String.Format(numberFormatInfo, "rgba({0:P}, {1:P}, {2:P}, {3:0.#})", arg.R / 255d, arg.G / 255d, arg.B / 255d, arg.A / 255d); } case "hsl": { return String.Format(numberFormatInfo, "hsl({0:F0}, {1:P}, {2:P})", arg.GetHue(), arg.GetSaturation(), arg.GetBrightness()); } case "hsla": { return String.Format(numberFormatInfo, "hsla({0:F0}, {1:P}, {2:P}, {3:0.#})", arg.GetHue(), arg.GetSaturation(), arg.GetBrightness(), arg.A / 255d); } default: { throw new FormatException(String.Format("Invalid format specified: \"{0}\".", format)); } } }
/// <summary> /// Gets a cool Highlight brush for highlighting things /// </summary> /// <param name="box">The rectangle in the box</param> /// <param name="selectionHighlight">The color to use for the higlight</param> /// <returns></returns> public static Brush HighlightBrush(Rectangle box, Color selectionHighlight) { float med = selectionHighlight.GetBrightness(); float bright = med + 0.05f; if (bright > 1f) bright = 1f; float dark = med - 0.05f; if (dark < 0f) dark = 0f; Color brtCol = ColorFromHsl(selectionHighlight.GetHue(), selectionHighlight.GetSaturation(), bright); Color drkCol = ColorFromHsl(selectionHighlight.GetHue(), selectionHighlight.GetSaturation(), dark); return new LinearGradientBrush(box, brtCol, drkCol, LinearGradientMode.Vertical); }
public void RGBtoHSL(int R, int G, int B) { System.Drawing.Color HSL = System.Drawing.Color.FromArgb(R, G, B); i_HSL_H = HSL.GetHue(); i_HSL_S = HSL.GetSaturation(); i_HSL_L = HSL.GetBrightness(); }
public HSLColor(Color color) { RGB = color; H = (byte)((color.GetHue() / 360.0f) * 255); S = (byte)(color.GetSaturation() * 255); L = (byte)(color.GetBrightness() * 255); }
private void getColour() { int r, g, b = 0; DialogResult result = GUI.colorDialog.ShowDialog(); if (result != DialogResult.Cancel) { color = GUI.colorDialog.Color; r = color.R; g = color.G; b = color.B; GUI.txtColourRGBdecimal.Text = r + ", " + g + ", " + b; GUI.txtColourRGB.Text = String.Format("{0:X2}", r) + String.Format("{0:X2}", g) + String.Format("{0:X2}", b); GUI.txtColourRGBcss.Text = "#" + String.Format("{0:X2}", r) + String.Format("{0:X2}", g) + String.Format("{0:X2}", b); GUI.txtColourRdec.Text = r.ToString(); GUI.txtColourGdec.Text = g.ToString(); GUI.txtColourBdec.Text = b.ToString(); GUI.txtColourRhex.Text = String.Format("{0:X2}", r); GUI.txtColourGhex.Text = String.Format("{0:X2}", g); GUI.txtColourBhex.Text = String.Format("{0:X2}", b); GUI.lblColourSample.BackColor = color; GUI.lblColourSample.Image = null; // RGB ->HSL conversion decimal h = decimal.Round(((decimal)(color.GetHue() / 360) * 240), MidpointRounding.AwayFromZero); decimal s = decimal.Round(((decimal)color.GetSaturation() * 240), MidpointRounding.AwayFromZero); decimal l = decimal.Round(((decimal)color.GetBrightness() * 240), MidpointRounding.AwayFromZero); GUI.txtColourH.Text = h.ToString(); GUI.txtColourS.Text = s.ToString(); GUI.txtColourL.Text = l.ToString(); } }
/// <summary> /// Initialize a new instance of the ColorHSL class. /// </summary> /// <param name="c">Initialize from an existing Color.</param> public ColorHSL(Color c) { // Initialize from the color instance _hue = c.GetHue() / 360f; _saturation = c.GetBrightness(); _luminance = c.GetSaturation(); }
private static void UpdateAutoSelect() { Skybound.VisualTips.Rendering.VisualTipOfficePreset visualTipOfficePreset; System.Drawing.Color color1 = System.Drawing.SystemColors.ActiveCaption; float f = color1.GetHue(); if ((f >= 200.0F) && (f <= 250.0F)) { visualTipOfficePreset = Skybound.VisualTips.Rendering.VisualTipOfficePreset.XPBlue; } else if ((f >= 70.0F) && (f <= 120.0F)) { visualTipOfficePreset = Skybound.VisualTips.Rendering.VisualTipOfficePreset.XPGreen; } else { if (f != 0.0F) { System.Drawing.Color color2 = System.Drawing.SystemColors.ActiveCaption; if (color2.GetSaturation() >= 0.1F) { goto label_1; } } visualTipOfficePreset = Skybound.VisualTips.Rendering.VisualTipOfficePreset.XPSilver; goto label_2; label_1: visualTipOfficePreset = Skybound.VisualTips.Rendering.VisualTipOfficePreset.Control; } label_2: Skybound.VisualTips.Rendering.VisualTipOfficePreset._AutoSelect = (Skybound.VisualTips.Rendering.VisualTipOfficePreset)visualTipOfficePreset.MemberwiseClone(); }
public static ColorSlider Saturation(VisualDirection direction, float knobWidth, float minVisualLength, Color color, Reaction<float> changed) { return new ColorSlider (direction, knobWidth, minVisualLength, 0f, 1f, color.GetSaturation (), new [] { Color.White, VisualHelpers.ColorFromHSB (color.GetHue (), 1f, color.GetBrightness ()) }, changed); }
public static void GetColorComponents(ColorModel colorModel, Color color, out Single componentA, out Single componentB, out Single componentC) { componentA = 0.0f; componentB = 0.0f; componentC = 0.0f; switch (colorModel) { case ColorModel.RedGreenBlue: componentA = color.R; componentB = color.G; componentC = color.B; break; case ColorModel.HueSaturationBrightness: componentA = color.GetHue(); componentB = color.GetSaturation(); componentC = color.GetBrightness(); break; case ColorModel.LabColorSpace: RGBtoLab(color.R, color.G, color.B, out componentA, out componentB, out componentC); break; case ColorModel.XYZ: RGBtoXYZ(color.R, color.G, color.B, out componentA, out componentB, out componentC); break; } }
public bool IsOldStar(Color pixelColor) { return ((pixelColor.GetHue() >= 150) && (pixelColor.GetHue() <= 258) && (pixelColor.GetSaturation() >= 0.10) && (pixelColor.GetBrightness() <= 0.90)); }
public async Task ColorCommand(float hue, float saturation, float value) { if (hue < 0f || hue > 360f) { await SendErrorAsync("The given hue must be between 0 and 360!"); return; } int hi = Convert.ToInt32(Math.Floor(hue / 60)) % 6; double f = hue / 60 - Math.Floor(hue / 60); int v = Convert.ToInt32(value * 255); int p = Convert.ToInt32(v * (1 - saturation)); int q = Convert.ToInt32(v * (1 - f * saturation)); int t = Convert.ToInt32(v * (1 - (1 - f) * saturation)); Color color = hi switch { 0 => Color.FromArgb(v, t, p), 1 => Color.FromArgb(q, v, p), 2 => Color.FromArgb(p, v, t), 3 => Color.FromArgb(p, q, v), 4 => Color.FromArgb(t, p, v), _ => Color.FromArgb(v, p, q) }; var builder = new EmbedBuilder() .AddField("RGB", $"Red: **{color.R}**\nGreen: **{color.G}**\nBlue: **{color.B}**", true) .AddField("HSV", $"Hue: **{hue}**\nSaturation: **{saturation}**\nValue: **{value}**", true) .AddField("HSL", $"Hue: **{hue}**\nSaturation: **{color.GetSaturation()}**\nLightness: **{color.GetBrightness()}**", true) .AddField("Hex Code", $"#{color.R:X2}{color.G:X2}{color.B:X2}"); await SendColorMessage(color, builder); }
private static double CalculateColorDifference(Color lhs, Color rhs) { double hue = lhs.GetHue() - rhs.GetHue(); double brightness = lhs.GetBrightness() - rhs.GetBrightness(); double saturation = lhs.GetSaturation() - rhs.GetSaturation(); return Math.Sqrt(hue * hue + brightness * brightness + saturation * saturation); }
/// <summary> /// Uses the saturation of the specified values to set the left and right values for this slider. /// </summary> /// <param name="startColor">The color that specifies the left saturation</param> /// <param name="endColor">The color that specifies the right saturation</param> public void SetSaturation(Color startColor, Color endColor) { float sStart = startColor.GetSaturation(); float sEnd = endColor.GetSaturation(); _inverted = sEnd < sStart; LeftValue = sStart; RightValue = sEnd; }
public HslColor(Color color) { _alpha = color.A; _hue = color.GetHue(); _saturation = color.GetSaturation(); _lightness = color.GetBrightness(); _isEmpty = false; }
private void ChangeColor(object sender, MouseButtonEventArgs e) { System.Windows.Point p = e.GetPosition(((IInputElement)e.Source)); if ((p.X >= 0) && (p.X < EditableImage.Width) && (p.Y >= 0) && (p.Y < EditableImage.Height)) { var bitmap = BitmapFromWriteableBitmap(EditableImage); System.Drawing.Color color = bitmap.GetPixel((int)p.X, (int)p.Y); var rr = -1; var gg = -1; var bb = -1; int r = 0; int g = 0; int b = 0; if (int.TryParse(R.Text, out rr) && rr >= 0 && rr < 256) { r = rr; } else { MessageBox.Show("Wrong Data"); } if (int.TryParse(R.Text, out gg) && gg >= 0 && gg < 256) { g = gg; } else { MessageBox.Show("Wrong Data"); } if (int.TryParse(R.Text, out bb) && bb >= 0 && bb < 256) { b = bb; } else { MessageBox.Show("Wrong Data"); } System.Drawing.Color colorToSet = System.Drawing.Color.FromArgb(r, g, b); float hue = color.GetHue(); float saturation = color.GetSaturation(); float brightness = color.GetBrightness(); bitmap = CreateNonIndexedImage(bitmap); bitmap.SetPixel(Convert.ToInt32(p.X), Convert.ToInt32(p.Y), colorToSet); EditableImage = WriteableBitmapBitmapFromBitmap(bitmap); Image.Source = EditableImage; } }
public static HSV ToHsv(this System.Drawing.Color c) { return(new HSV() { H = c.GetHue(), S = c.GetSaturation(), V = c.GetBrightness(), }); }
/// <summary> /// Initializes a new instance of the <see cref="DistinctColorInfo"/> struct. /// </summary> public DistinctColorInfo(Color color) { Color = color.ToArgb(); Count = 1; Hue = Convert.ToInt32(color.GetHue()*Factor); Saturation = Convert.ToInt32(color.GetSaturation()*Factor); Brightness = Convert.ToInt32(color.GetBrightness()*Factor); }
public static System.Drawing.Color ModulateColor(System.Drawing.Color color, float mod) { float h = color.GetHue() / 360.0f; float s = color.GetSaturation(); float l = color.GetBrightness(); l += mod; l = Math.Min(l, 1.0f); double r = 0, g = 0, b = 0; double temp1, temp2; temp2 = ((l <= 0.5) ? l * (1.0 + s) : l + s - (l * s)); temp1 = 2.0 * l - temp2; double[] t3 = new double[] { h + 1.0 / 3.0, h, h - 1.0 / 3.0 }; double[] clr = new double[] { 0, 0, 0 }; for (int i = 0; i < 3; i++) { if (t3[i] < 0) { t3[i] += 1.0; } if (t3[i] > 1) { t3[i] -= 1.0; } if (6.0 * t3[i] < 1.0) { clr[i] = temp1 + (temp2 - temp1) * t3[i] * 6.0; } else if (2.0 * t3[i] < 1.0) { clr[i] = temp2; } else if (3.0 * t3[i] < 2.0) { clr[i] = (temp1 + (temp2 - temp1) * ((2.0 / 3.0) - t3[i]) * 6.0); } else { clr[i] = temp1; } } clr[0] = Math.Max(Math.Min(clr[0], 1.0), 0.0); clr[1] = Math.Max(Math.Min(clr[1], 1.0), 0.0); clr[2] = Math.Max(Math.Min(clr[2], 1.0), 0.0); r = clr[0] * 255.0; g = clr[1] * 255.0; b = clr[2] * 255.0; return(System.Drawing.Color.FromArgb(color.A, (int)r, (int)g, (int)b)); }
// /// <summary> /// Converts RGB to HSL /// </summary> /// <remarks>Takes advantage of whats already built in to .NET by using the Color.GetHue, Color.GetSaturation and Color.GetBrightness methods</remarks> /// <param name="c">A Color to convert</param> /// <returns>An HSL value</returns> public static HSL GetHSL(Color c) { HSL hsl = new HSL(); hsl.H = c.GetHue() / 360.0; // we store hue as 0-1 as opposed to 0-360 hsl.L = c.GetBrightness(); hsl.S = c.GetSaturation(); return hsl; }
/// <summary> /// Constructor with ARGB color /// </summary> /// <param name="color">System.Drawing.Color value</param> public HSL(Color color) { try { this.HSLHelper(color.GetHue() / 360.0, color.GetSaturation(), color.GetBrightness()); } catch (Exception ee) { throw new GFXConversionException("HSL Constructor Error", ee); } }
public DialogResult ShowDlg(Color baseColor) { if(baseColor != null) { selHSLColor.Hue = baseColor.GetHue(); selHSLColor.Saturation = baseColor.GetSaturation(); selHSLColor.Lightness = baseColor.GetBrightness(); selHSLColor.Color = baseColor; lblFinalColorValue.BackColor = baseColor; } return ShowDialog(); }
public Tone GetTone(Color pixel) { float hue = pixel.GetHue(); float brightness = pixel.GetBrightness(); float saturation = pixel.GetSaturation(); var frequency = ConvertToFrequency(hue); var duration = ConvertToDuration(brightness); var volume = ConvertToVolume(saturation); //var duration = ConvertToDuration(saturation); //var volume = ConvertToVolume(brightness); return new Tone {Frequency = frequency, Duration = duration, Volume = volume}; }
public static void GetColorComponents(ColorModel colorModel, Color color, Color targetColor, out Single componentA, out Single componentB, out Single componentC) { componentA = 0.0f; componentB = 0.0f; componentC = 0.0f; switch (colorModel) { case ColorModel.RedGreenBlue: componentA = color.R - targetColor.R; componentB = color.G - targetColor.G; componentC = color.B - targetColor.B; break; case ColorModel.HueSaturationBrightness: componentA = color.GetHue() - targetColor.GetHue(); componentB = color.GetSaturation() - targetColor.GetSaturation(); componentC = color.GetBrightness() - targetColor.GetBrightness(); break; case ColorModel.LabColorSpace: Single sourceL, sourceA, sourceB; Single targetL, targetA, targetB; RGBtoLab(color.R, color.G, color.B, out sourceL, out sourceA, out sourceB); RGBtoLab(targetColor.R, targetColor.G, targetColor.B, out targetL, out targetA, out targetB); componentA = sourceL - targetL; componentB = sourceA - targetA; componentC = sourceB - targetB; break; case ColorModel.XYZ: Single sourceX, sourceY, sourceZ; Single targetX, targetY, targetZ; RGBtoXYZ(color.R, color.G, color.B, out sourceX, out sourceY, out sourceZ); RGBtoXYZ(targetColor.R, targetColor.G, targetColor.B, out targetX, out targetY, out targetZ); componentA = sourceX - targetX; componentB = sourceY - targetY; componentC = sourceZ - targetZ; break; } }
internal static ConsoleColor GetConsoleColor(Color color) { if (color.GetSaturation() < 0.5) { // we have a grayish color switch ((int)(color.GetBrightness()*3.5)) { case 0: return ConsoleColor.Black; case 1: return ConsoleColor.DarkGray; case 2: return ConsoleColor.Gray; default: return ConsoleColor.White; } } int hue = (int)Math.Round(color.GetHue()/60, MidpointRounding.AwayFromZero); if (color.GetBrightness() < 0.4) { // dark color switch (hue) { case 1: return ConsoleColor.DarkYellow; case 2: return ConsoleColor.DarkGreen; case 3: return ConsoleColor.DarkCyan; case 4: return ConsoleColor.DarkBlue; case 5: return ConsoleColor.DarkMagenta; default: return ConsoleColor.DarkRed; } } // bright color switch (hue) { case 1: return ConsoleColor.Yellow; case 2: return ConsoleColor.Green; case 3: return ConsoleColor.Cyan; case 4: return ConsoleColor.Blue; case 5: return ConsoleColor.Magenta; default: return ConsoleColor.Red; } }
/// <summary> /// checks if pixol is grayscale /// </summary> /// <param name="pixol">the pixol to check</param> /// <returns>true- if grayscale, false- otherwise</returns> private bool grayscale(System.Drawing.Color pixol) { double mean, sd; mean = pixol.B + pixol.G + pixol.R; sd = Math.Sqrt((Math.Pow((mean - pixol.B), 2) + Math.Pow((mean - pixol.G), 2) + Math.Pow((mean - pixol.R), 2)) / 3); if (pixol.B < GrayThreshold * sd && pixol.G < GrayThreshold * sd && pixol.R < GrayThreshold * sd || pixol.GetSaturation() < SaturationThreshold && (pixol.GetBrightness() > BlackBrightnessThreshold)) { return(true); } else { return(false); } }
public void MainColorCanvas_SelectedColorChanged(object sender, EventArgs e) { System.Windows.Media.Color mediaColor = (System.Windows.Media.Color)Main_ColorCanvas.SelectedColor; System.Drawing.Color drawingColor = System.Drawing.Color.FromArgb(mediaColor.A, mediaColor.R, mediaColor.G, mediaColor.B); HexCode_TextBox.Text = GetHex(drawingColor); HashCode_TextBox.Text = mediaColor.GetHashCode().ToString(); Brightness_TextBox.Text = (drawingColor.GetBrightness() * 100).ToString() + "%"; Saturation_TextBox.Text = (drawingColor.GetSaturation() * 100).ToString() + "%"; Hue_TextBox.Text = drawingColor.GetHue().ToString() + "°"; RP_TextBox.Text = (Math.Round(drawingColor.R / 256.0, 4) * 100).ToString() + "%"; GP_TextBox.Text = (Math.Round(drawingColor.G / 256.0, 4) * 100).ToString() + "%"; BP_TextBox.Text = (Math.Round(drawingColor.B / 256.0, 4) * 100).ToString() + "%"; RM_TextBox.Text = drawingColor.R.ToString(); GM_TextBox.Text = drawingColor.G.ToString(); BM_TextBox.Text = drawingColor.B.ToString(); }
private void MouseMove(object sender, MouseEventArgs e) { System.Windows.Point p = e.GetPosition(((IInputElement)e.Source)); if ((p.X >= 0) && (p.X < EditableImage.Width) && (p.Y >= 0) && (p.Y < EditableImage.Height)) { System.Drawing.Color color = BitmapFromWriteableBitmap(EditableImage).GetPixel((int)p.X, (int)p.Y); int r = color.R; int g = color.G; int b = color.B; float hue = color.GetHue(); float saturation = color.GetSaturation(); float brightness = color.GetBrightness(); RGB.Text = String.Format("R: {0} G: {1} B: {2}", r.ToString(), g.ToString(), b.ToString()); } }
// Event of changeing the text in the HexColorIO TextBox private void toolStripTextBoxHexColorIO_TextChanged(object sender, EventArgs e) { try { System.Drawing.Color rgbColor = System.Drawing.Color.White; rgbColor = ColorTranslator.FromHtml(((ToolStripTextBox)sender).Text); ((ToolStripTextBox)sender).BackColor = rgbColor; HSLColor hslColor = new HSLColor(240 - rgbColor.GetHue(), rgbColor.GetSaturation(), 240); ((ToolStripTextBox)sender).ForeColor = hslColor; string trimedHex = ((ToolStripTextBox)sender).Text.TrimStart('#'); if (trimedHex.Length >= 6) { SetPenumbraColors(true); } } catch { } }
private void update_square() { brush = new SolidBrush(Color.FromArgb(trackBar1.Value, trackBar2.Value, trackBar3.Value)); g.FillRectangle(brush, rect); label1.Text = "Red : " + trackBar1.Value.ToString(); label2.Text = "Green : " + trackBar2.Value.ToString(); label3.Text = "Blue : " + trackBar3.Value.ToString(); double c = 1 - ((double)trackBar1.Value / 255); double m = 1 - ((double)trackBar2.Value / 255); double k = 1 - ((double)trackBar3.Value / 255); label4.Text = "C: " + c.ToString() + "M: " + m.ToString() + "K: " + k.ToString(); System.Drawing.Color color = System.Drawing.Color.FromArgb(trackBar1.Value, trackBar2.Value, trackBar3.Value); float hue = color.GetHue(); float saturation = color.GetSaturation(); float lightness = color.GetBrightness(); label6.Text = "H: " + hue.ToString() + "S: " + saturation.ToString() + "V: " + lightness.ToString(); }
/// <summary> /// Sends a state command to a hue bridge. /// </summary> /// <param name="bridgeip">IP address of the hue bridge.</param> /// <param name="username">Username to authenticate with.</param> /// <param name="color">A Color object representing the color to set.</param> /// <param name="light">An int value representing the light ID to change.</param> /// <param name="transitionspeed">The speed at which the transition should occur.</param> public void hueset(string bridgeip, string username, Color color, int light, int transitionspeed) { //Get the HSV Value from the currently selected color //var hsv = LightColorSlider.Color.GetHSV(); //build our State object Tools.Log Log = new Tools.Log(); var state = new { on = true, hue = (int)(color.GetHue() * 182.04), //we convert the hue value into degrees by multiplying the value by 182.04 sat = (int)(color.GetSaturation() * 254), transitiontime = (int)transitionspeed }; //convert it to json: var jsonObj = JsonConvert.SerializeObject(state); //set the api url to set the state var uri = new Uri(string.Format("http://{0}/api/{1}/lights/{2}/state", bridgeip, username, light)); var client = new WebClient(); //decide what to do with the response we get back from the bridge client.UploadStringCompleted += (o, args) => { try { Log.Write(Properties.Resources.LOG_HUE_BRIDGE_RESPONSE + " " + args.Result); } catch (Exception ex) { Log.Write(Properties.Resources.LOG_HUE_BRIDGE_EXCEPTION + " " + ex.Message); } }; //Invoke the PUT method to set the state of the bulb client.UploadStringAsync(uri, "PUT", jsonObj); }
private void histogramProcess_Click(object sender, EventArgs e) { long[] matImage = new long[256]; long[] matSum = new long[256]; long pixelValues = 0; long sumValue = 0; Bitmap bmpHisto = (Bitmap)bmpOrig.Clone(); for (int i = 0; i < bmpHisto.Height; i++) { for (int j = 0; j < bmpHisto.Width; j++) { pixelValues = (long)(255 * bmpHisto.GetPixel(j, i).GetBrightness()); matImage[pixelValues]++; } } label1.Text = matImage[3].ToString(); for (int level = 0; level < 256; level++) { sumValue = sumValue + matImage[level]; matSum[level] = sumValue; } for (int i = 0; i < bmpHisto.Height; i++) { for (int j = 0; j < bmpHisto.Width; j++) { System.Drawing.Color clr = bmpHisto.GetPixel(j, i); pixelValues = (long)(255 * clr.GetSaturation()); pixelValues = (long)(255f / (bmpHisto.Width * bmpHisto.Height) * matSum[pixelValues] - pixelValues); int R = (int)Math.Min(255, clr.R + pixelValues / 3); //.299 int G = (int)Math.Min(255, clr.G + pixelValues / 3); //.587 int B = (int)Math.Min(255, clr.B + pixelValues / 3); //.112 bmpHisto.SetPixel(j, i, System.Drawing.Color.FromArgb(Math.Max(R, 0), Math.Max(G, 0), Math.Max(B, 0))); } } orgPicture.Image = bmpOrig; histogram.Image = bmpHisto; }
public Gif Rainbow(Bitmap b, IMessage m) { Vector3[,] HSVimage = new Vector3[b.Width, b.Height]; int[,] Alphas = new int[b.Width, b.Height]; using (UnsafeBitmapContext c = ImageExtensions.CreateUnsafeContext(b)) for (int x = 0; x < b.Width; x++) { for (int y = 0; y < b.Height; y++) { Color col = c.GetPixel(x, y); Alphas[x, y] = col.A; HSVimage[x, y] = new Vector3(col.GetHue(), col.GetSaturation(), col.GetValue()); } } int steps = 20; int stepWidth = 360 / steps; Bitmap[] re = new Bitmap[steps]; for (int i = 0; i < steps; i++) { re[i] = new Bitmap(b.Width, b.Height); using UnsafeBitmapContext c = ImageExtensions.CreateUnsafeContext(re[i]); for (int x = 0; x < b.Width; x++) { for (int y = 0; y < b.Height; y++) { c.SetPixel(x, y, Color.FromArgb(Alphas[x, y], HSVimage[x, y].HsvToRgb())); HSVimage[x, y].X += stepWidth; while (HSVimage[x, y].X > 360) { HSVimage[x, y].X -= 360; } } } } return(new Gif(re, Enumerable.Repeat(33, re.Length).ToArray())); }
public float GetColorDistance(Color aColor) { float srcH = aColor.GetHue(); float srcS = aColor.GetSaturation(); float srcV = aColor.GetBrightness(); float ratH = rasterColor.GetHue(); float ratS = rasterColor.GetSaturation(); float ratV = rasterColor.GetBrightness(); float hueDist = Math.Min( Math.Abs(srcH-ratH), (Math.Abs( (Math.Min(ratH, srcH)+360) - Math.Max(ratH, srcH) )) ) /360*100;//procent float satDist = Math.Abs(srcS-ratS)*100; float valDist = Math.Abs(srcV-ratV)*100; float result = (hueDist*hueDist + satDist + valDist * valDist) / gravity; return result; }
public async Task ColorCommand(int red, int green, int blue) { if (red > byte.MaxValue || red < byte.MinValue || green > byte.MaxValue || green < byte.MinValue || blue > byte.MaxValue || blue < byte.MinValue) { await SendErrorAsync("The red, green and blue values must be integers between 0 and 255."); return; } Color color = Color.FromArgb(red, green, blue); color.GetHsv(out float hue, out float saturation, out float value); var builder = new EmbedBuilder() .AddField("RGB", $"Red: **{color.R}**\nGreen: **{color.G}**\nBlue: **{color.B}**", true) .AddField("HSV", $"Hue: **{hue}**\nSaturation: **{saturation}**\nValue: **{value}**", true) .AddField("HSL", $"Hue: **{color.GetHue()}**\nSaturation: **{color.GetSaturation()}**\nLightness: **{color.GetBrightness()}**", true) .AddField("Hex Code", $"#{color.R:X2}{color.G:X2}{color.B:X2}"); await SendColorMessage(color, builder); }
public CurrentCursorDetails GetPixelInfoAroundMousePosition(int OffsetX, int OffsetY) { Point cursor = new Point(); GetCursorPos(ref cursor); var bitmap = new Bitmap(OffsetX * 2, OffsetY * 2); var gfxScreenshot = Graphics.FromImage(bitmap); gfxScreenshot.CopyFromScreen(cursor.X - OffsetX, cursor.Y - OffsetY, cursor.X + OffsetX, cursor.Y - OffsetY, bitmap.Size); System.Drawing.Color col = CalculateAverageColor(bitmap); CurrentCursorDetails res = new CurrentCursorDetails { PosX = cursor.X, PosY = cursor.Y, Red = col.R, Green = col.G, Blue = col.B, Hue = col.GetHue(), Saturation = col.GetSaturation(), Brightness = col.GetBrightness() }; return(res); }
/// <summary> /// 对原图进行基准白矫正1,效率比较低 /// </summary> /// <param name="bitimg"></param> /// <returns></returns> static public Bitmap NormalizedWhite(Bitmap bitimg) { Bitmap myimg = bitimg; int m = bitimg.Width; int n = bitimg.Height; double[,] H = new double[m, n]; double maxH = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { byte red = bitimg.GetPixel(i, j).R; byte green = bitimg.GetPixel(i, j).G; byte blue = bitimg.GetPixel(i, j).B; System.Drawing.Color color = System.Drawing.Color.FromArgb(red, green, blue); double hue = color.GetHue(); //double hue = 0.299*(double)red + 0.587*(double)green + 0.114*(double)blue; //double Cb = 0.564*((double)blue - hue); //double Cr = 0.713 * ((double)red - hue); if (maxH < hue)//找到最大的亮度数值 { maxH = hue; } H[i, j] = hue; float saturation = color.GetSaturation(); float lightness = color.GetBrightness(); } } double[] sortedH = new double[(int)maxH + 1];//用来存档排序后的亮度值 double sumI = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { sortedH[(int)H[i, j]]++; sumI += H[i, j];//求出图像的所有亮度和 } } double meanI = sumI / (m * n); //求出图像的平均亮度值 int count = (int)(sortedH.Count() * 0.05); //数据的总数n float sumR = 0; float sumG = 0; float sumB = 0; int countRGB = 0; for (int i = sortedH.Count(); i > sortedH.Count() - count; i--) { for (int ii = 0; ii < m; ii++)//遍历所有的图片像素 { for (int iii = 0; iii < n; iii++) { if (H[ii, iii] == i)//找到一样的像素 { sumR += bitimg.GetPixel(ii, iii).R; sumG += bitimg.GetPixel(ii, iii).G; sumB += bitimg.GetPixel(ii, iii).B; countRGB++; } } } } double meanR = sumR / countRGB; //基准白的R均值 double meanG = sumG / countRGB; //基准白的G均值 double meanB = sumB / countRGB; //基准白的B均值 double aR = meanR / meanG; //调整系数 double aG = meanG / meanI; double aB = meanB / meanI; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { int colorR = (int)(bitimg.GetPixel(i, j).R *aR); int colorG = (int)(bitimg.GetPixel(i, j).G *aG); int colorB = (int)(bitimg.GetPixel(i, j).B *aB); int cR; int cG; int cB; if (double.IsNaN(aR * aG * aB)) { cR = double.IsNaN(aR) ? bitimg.GetPixel(i, j).R : colorR; cG = double.IsNaN(aG) ? bitimg.GetPixel(i, j).G : colorG; cB = double.IsNaN(aG) ? bitimg.GetPixel(i, j).B : colorB; } else { cR = colorR > 255 ? 255 : colorR; cG = colorG > 255 ? 255 : colorG; cB = colorB > 255 ? 255 : colorB; } Color cnew = Color.FromArgb(cR, cG, cB); myimg.SetPixel(i, j, cnew); } } //进行排序 return(myimg); }
/// <summary> /// Converts RGB to HSL /// </summary> /// <remarks>Takes advantage of whats already built in to .NET by using the Color.GetHue, Color.GetSaturation and Color.GetBrightness methods</remarks> /// <param name="c">A Color to convert</param> /// <returns>An HSL value</returns> public static HSL RGB2HSL( Color c ) { return new HSL( c.GetHue()/360.0, c.GetSaturation(), c.GetBrightness() ); }
private void HandleUnitSelection() { Vector2 temp = endBoxPos - orgBoxPos; Rectangle rect = new Rectangle((int)orgBoxPos.x, 480 - (int)(orgBoxPos.y), (int)(Mathf.Abs(temp.x)), (int)(Mathf.Abs(temp.y))); test = new Mat(frame, rect); Image <Bgr, Byte> imgBgr = test.ToImage <Bgr, byte>(); var moments = CvInvoke.Moments(imgBgr[0]); int cx = (int)(moments.M10 / moments.M00); int cy = (int)(moments.M01 / moments.M00); int b = 0, g = 0, r = 0; for (int i = 0; i < 5; i++) { Point pts1 = new Point(cx + i, cy + i); Point pts2 = new Point(cx - i, cy - i); Point pts3 = new Point(cx - i, cy + i); Point pts4 = new Point(cx + i, cy - i); r += (int)imgBgr[pts1].Red; r += (int)imgBgr[pts2].Red; r += (int)imgBgr[pts3].Red; r += (int)imgBgr[pts4].Red; g += (int)imgBgr[pts1].Green; g += (int)imgBgr[pts2].Green; g += (int)imgBgr[pts3].Green; g += (int)imgBgr[pts4].Green; b += (int)imgBgr[pts1].Blue; b += (int)imgBgr[pts2].Blue; b += (int)imgBgr[pts3].Blue; b += (int)imgBgr[pts4].Blue; } r = r / 20; g = g / 20; b = b / 20; System.Drawing.Color c = System.Drawing.Color.FromArgb(r, g, b); Hsv hsv = new Hsv(c.GetHue(), c.GetSaturation(), c.GetBrightness()); hTarget = hsv.Hue / 2; sTarget = hsv.Satuation; vTarget = hsv.Value; Mat tata = test.Clone(); CvInvoke.CvtColor(test, tata, ColorConversion.Bgr2Hsv); Image <Hsv, byte> ImgHSV = tata.ToImage <Hsv, byte>(); Image <Gray, byte> tarace = ImgHSV.InRange(new Hsv(hTarget - intensity, 0, 0), new Hsv(hTarget + intensity, 255, 255)); Mat hierarchy = new Mat(); VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint(); CvInvoke.FindContours(tarace, contours, hierarchy, RetrType.List, ChainApproxMethod.ChainApproxNone); double biggestContourArea = 0; VectorOfPoint biggestContour = new VectorOfPoint(); int biggestContourIndex = 0; for (int i = 0; i < contours.Size; i++) { if (CvInvoke.ContourArea(contours[i]) > biggestContourArea) { biggestContour = contours[i]; biggestContourIndex = i; biggestContourArea = CvInvoke.ContourArea(contours[i]); } } Mat biggestContourMat = new Mat(test, CvInvoke.BoundingRectangle(contours[biggestContourIndex])); CvInvoke.Mean() // colorDetect = true; }
public static HSB RGB2HSB (Color color) { HSB hsb = new HSB (); hsb.hue = (int)((color.GetHue () / 360.0f) * 240); hsb.sat = (int)(color.GetSaturation () * 241); hsb.bri = (int)(color.GetBrightness () * 241); if (hsb.hue > 239) hsb.hue = 239; if (hsb.sat > 240) hsb.sat = 240; if (hsb.bri > 240) hsb.bri = 240; return hsb; }
public static void GetHueSaturation (Color color, out int hue, out int sat) { hue = (int)((color.GetHue () / 360.0f) * 240); sat = (int)(color.GetSaturation () * 241); }
public static HSL FromRGB(Color c) { return new HSL(c.GetHue(), c.GetSaturation(), c.GetBrightness()); }
public HSL(Color c) : this(c.GetHue() / 360.0, c.GetSaturation(), c.GetBrightness()) { }
private static Color applyRatio(Color c1, Color c2, uint r) { float ratio = r / 100f; float hue1 = c1.GetHue(); float hue2 = c2.GetHue(); float bri1 = c1.GetBrightness(); float bri2 = c2.GetBrightness(); float sat1 = c1.GetSaturation(); float sat2 = c2.GetSaturation(); float hr = hue2 - hue1; float br = bri2 - bri1; float sr = sat2 - sat1; Color csR = bri1 == 0 ? HuetoRGB(hue2, sat2, bri2 - br * ratio) : HuetoRGB(hue2 - hr * ratio, sat2 - sr * ratio, bri2 - br * ratio); return csR; }
Color GetNearestOfBWR(Color c,ref Bitmap imageoriginal) { float redness = Math.Abs(180 - c.GetHue()) / 180; float brightness = c.GetBrightness(); float saturation = c.GetSaturation(); double brightColourfulRedness = Math.Sqrt(redness * redness + brightness * brightness + saturation * saturation); if (brightColourfulRedness > 1) return Color.FromArgb(255, 0, 0); // red; if (brightness > 0.5) return Color.FromArgb(255, 255, 255); // white return Color.FromArgb(0, 0, 0); // black }
public static HSLColor FromArgbColor(Color c) { //double r = (double)c.R / 255; //double g = (double)c.G / 255; //double b = (double)c.B / 255; //double h, s, l; //double Cmax = Math.Max(r, Math.Max(g, b)); //double Cmin = Math.Min(r, Math.Min(g, b)); //double d = Cmax - Cmin; //l = ((Cmax + Cmin) / 2 * 100); //if (d == 0) //{ // h = s = 0; //} //else //{ // h = ((Cmax == r ? ((g - b) / d) + (g < b ? 6 : 0) : Cmax == g ? ((b - r) / d) + 2 : ((r - g) / d) + 4) * 60); // //_s = (int)(d / (1 - Math.Abs(2 * _l - 1)) * 100); // s = ((l > 50 ? d / (2 - Cmax - Cmin) : d / (Cmax + Cmin)) * 100); //} double h = c.GetHue(); double s = c.GetSaturation(); double l = c.GetBrightness(); return new HSLColor(h, s, l); }
private async void CreateCode_Button(object sender, RoutedEventArgs e) { if (openflag == false) { MessageBox.Show("開くファイルを選択してください", "コード生成エラー", MessageBoxButton.OK, MessageBoxImage.Information); return; } Bitmap bitmap = new Bitmap(Filepath); //描画用クラスのインスタンス化 int w = bitmap.Width; //画素の幅 int h = bitmap.Height; //画素の高さ progress.Minimum = 0; //最小値は0 progress.Maximum = h; //高さの分が最大値 if (w > 128 || h > 128) { MessageBox.Show("幅または高さが 128[px] を超えているものは生成できません。", "コード生成エラー", MessageBoxButton.OK, MessageBoxImage.Information); return; } status.Content = "ステータス:生成中..."; Textbox_code.Text = ""; Textbox_code.Text += "#define P_WIDTH " + w.ToString() + "\n"; Textbox_code.Text += "#define P_HEIGHT " + h.ToString() + "\n\n"; Textbox_code.Text += "const unsigned int pic_data[P_HEIGHT][P_WIDTH] = {\n"; for (int y = 0; y < h; y++) { Textbox_code.Text += "\t"; //タブスペース "\t" Textbox_code.Text += "{"; for (int x = 0; x < w; x++) { System.Drawing.Color pixel = bitmap.GetPixel(x, y); float H = pixel.GetHue(); float S = pixel.GetSaturation(); //0に行くほど白 float B = pixel.GetBrightness(); //0にいくほど黒 await Task.Run(() => { Color_value = ConvertColor(H, S, B); }); //Textbox_code.Text += "[" + H.ToString()+ " " + S.ToString() + " " + B.ToString() + "]"; //数値確認 Textbox_code.Text += Color_value.ToString(); if (x == w - 1) { Textbox_code.Text += ""; } else { Textbox_code.Text += ", "; } } //Invoke は他のタスクで使用されているコントローラに操作する権利を与える //非同期処理で進捗率も示す。 await Task.Run(() => { Dispatcher.Invoke((Action)(() => { progress.Value = y + 1; })); }); Textbox_code.Text += "},\n"; } Textbox_code.Text += "};\n"; saveflag = true; status.Content = "ステータス:完了"; }
public void update(System.Drawing.Color c) { if (c == Color.Empty) { updateUI(string.Empty); return; } HSLString = c.GetHue().ToString("N2", CultureInfo.InvariantCulture) + ", " + c.GetSaturation().ToString("N2", CultureInfo.InvariantCulture) + ", " + c.GetBrightness().ToString("N2", CultureInfo.InvariantCulture); updateUI(HSLString); }
protected override Color ModifyColorByState(Color color) { color = base.ModifyColorByState(color); var hue = color.GetHue(); var saturation = color.GetSaturation(); var brightness = color.GetBrightness(); if (IsSelected) { hue = (hue + 60) % 360; } return ColorHelper.FromAHSB(color.A, hue, saturation, brightness); }
public static void DrawWallpaper(Graphics graphics, Rectangle rect, Color light, Color shadow) { float angle = (float)(Math.Atan2(rect.Width, rect.Height) * 180 / Math.PI); var screenRect = rect.Deflated(3, 3); var wpBrush = new LinearGradientBrush(rect, light, shadow, angle); var shadowColorA = ColorF.FromHSLA(shadow.GetHue() / 360, shadow.GetSaturation() * 2, shadow.GetBrightness() / 4, 0.5); var shadowColorB = ColorF.FromHSLA(light.GetHue() / 360, light.GetSaturation() * 2, light.GetBrightness() / 4, 0.5); var shadowPen = new Pen(new LinearGradientBrush(rect, shadowColorA, shadowColorB, angle)); var shadowColorC = (shadowColorA + shadowColorB) / 2; shadowColorC.A /= 2; var innerShadowPen = new Pen(shadowColorC); graphics.FillRectangle(wpBrush, screenRect); graphics.DrawRectangle(innerShadowPen, 4, 3, rect.Width - 9, rect.Height - 6); graphics.DrawRectangle(shadowPen, screenRect.Deflated(0, 0, 1, 1)); }
public override IEnumerator StartSpell() { int x = 0; const float target_comp = 23; const float b = 1.17f; const float start_comp = 12; const float comp_speed = 0.09f; const float path_threshold = 3f; float current_comp; float comp_accuracy; bool calcp = true; while (true) { ShootSFX(); if (calcp) { comp_accuracy = start_comp * Mathf.Pow(b, -x * comp_speed); if (comp_accuracy < 0.001f) { calcp = false; } current_comp = target_comp - comp_accuracy; } else { current_comp = target_comp; } float path = 7 * Mathf.Sin(current_comp * x * Mathf.Deg2Rad) + 9; int layerNum = 1; bool flip = false; for (int y = -3; y < 24; y++) { if (Mathf.Abs(y - path) <= path_threshold) { flip = true; continue; } GameObject bullet; if (Mathf.Abs(y + 1 - path) <= path_threshold || Mathf.Abs(y - 1 - path) <= path_threshold) { // If on edges, use the edge bullet bullet = ObjectPooler.Spawn("LevelBarEnd", new Vector3(15, y, 0), Quaternion.identity); } else { bullet = ObjectPooler.Spawn("LevelBarBody", new Vector3(15, y, 0), Quaternion.identity); } if (flip) { bullet.transform.Rotate(0, 0, 180); } SpriteRenderer rend = bullet.GetComponent <SpriteRenderer>(); rend.sortingOrder = layerNum++; System.Drawing.Color c = System.Drawing.Color.FromArgb((int)(rend.color.r * 255), (int)(rend.color.g * 255), (int)(rend.color.b * 255)); float hue = (c.GetHue() + x * 1.5f) % 360 / 360f; float sat = c.GetSaturation(); // float bri = c.GetBrightness(); rend.color = Color.HSVToRGB(hue, sat, 1); bullet.GetComponent <Rigidbody2D>().velocity = new Vector2(-4, 0); } x++; yield return(new WaitForSeconds(0.25f)); } }