GetBrightness() public method

public GetBrightness ( ) : float
return float
Exemplo n.º 1
0
		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));
					}
			}
		}
Exemplo n.º 2
0
        /// <summary>
        /// This method draws a cross at the given position.
        /// </summary>
        /// <param name="image">The input image.</param>
        /// <param name="point">The position of the cross.</param>
        /// <param name="size">The size of the cross.</param>
        /// <param name="color">The color of the cross.</param>
        /// <param name="thickness">The thickness of the cross.</param>
        private void DrawCross(Image <Gray, byte> image, Point point, int size, System.Drawing.Color color, int thickness)
        {
            // Convert to System.Drawing.Point until EMGU updates its library
            System.Drawing.Point p1 = new System.Drawing.Point((int)point.X - (int)(size / 2), (int)point.Y);
            System.Drawing.Point p2 = new System.Drawing.Point((int)point.X + (int)(size / 2), (int)point.Y);

            image.Draw(new LineSegment2D(p1, p2), new Gray(color.GetBrightness()), thickness);

            System.Drawing.Point p3 = new System.Drawing.Point((int)point.X, (int)point.Y - (int)(size / 2));
            System.Drawing.Point p4 = new System.Drawing.Point((int)point.X, (int)point.Y + (int)(size / 2));

            image.Draw(new LineSegment2D(p3, p4), new Gray(color.GetBrightness()), thickness);
        }
Exemplo n.º 3
0
		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;
			}
		}
Exemplo n.º 4
0
 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();
     }
 }
Exemplo n.º 5
0
        public static Bitmap BitmapTo1Bpp(Bitmap img)
        {
            int        w    = img.Width;
            int        h    = img.Height;
            Bitmap     bmp  = new Bitmap(w, h, System.Drawing.Imaging.PixelFormat.Format1bppIndexed);
            BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format1bppIndexed);

            byte[] scan = new byte[(w + 7) / 8];
            for (int y = 0; y < h; y++)
            {
                for (int x = 0; x < w; x++)
                {
                    if (x % 8 == 0)
                    {
                        scan[x / 8] = 0;
                    }
                    System.Drawing.Color c = img.GetPixel(x, y);
                    if (c.GetBrightness() >= 0.5)
                    {
                        scan[x / 8] |= (byte)(0x80 >> (x % 8));
                    }
                }
                Marshal.Copy(scan, 0, (IntPtr)((long)data.Scan0 + data.Stride * y), scan.Length);
            }
            bmp.UnlockBits(data);
            return(bmp);
        }
        private void click_button(object sender, RoutedEventArgs e)
        {
            List <string> FileWritte = new List <string>();

            Bitmap HeatMapBitmap  = new Bitmap(ExcelFileTxtBox.Text);
            Bitmap OrgnlPicBitmap = new Bitmap(ExcelFileTxtBox_Copy.Text);
            int    n = HeatMapBitmap.Height;
            int    m = HeatMapBitmap.Width;

            int[,,] arrayImg = new int[n, m, 3];
            for (int x = 0; x < HeatMapBitmap.Width; x++)
            {
                for (int y = 0; y < HeatMapBitmap.Height; y++)
                {
                    Color pixelColor     = HeatMapBitmap.GetPixel(x, y);
                    Color pixelColorCopy = OrgnlPicBitmap.GetPixel(x, y);
                    float b = pixelColor.GetBrightness() * 3000;
                    FileWritte.Add(x.ToString() + "," + y.ToString() + "," + b.ToString() + "," + pixelColorCopy.R.ToString() + "," + pixelColorCopy.G.ToString() + "," + pixelColorCopy.B.ToString() + "," + Environment.NewLine);
                }
            }

            string combindedString = string.Join("-", FileWritte);
            string path            = @"C:\Users\V. Noves\Downloads\Test.txt";

            File.AppendAllLines(path, new[] { combindedString });
            MessageBox.Show("Succes", "Success");
        }
        private void checkPixel(int xp, int yp, bool goUp, double factor)
        {
            System.Drawing.Color qrColor = qrCodeImage.GetPixel(xp, yp); // Get pixel color
//            Logger.Trace("checkPixel x:{0} y:{1} color:{2} last1:{3}", xp, yp, qrColor, last1);
            int ycnc = qrCodeImage.Height - yp;                          // vertical flip
            int dir  = 0;

            if (!goUp)
            {
                dir = -1;
            }

            bool isBlack = (qrColor.GetBrightness() < 0.5);

            if (isBlack)
            {
                if (!lastWasBlack)
                {
                    Graphic.StartPath(new System.Windows.Point(factor * xp, factor * (ycnc + dir)));         // start new on bottom
                }
                lastWasBlack = true;
            }
            else
            {
                if (lastWasBlack)
                {
                    Graphic.AddLine(new System.Windows.Point(factor * xp, factor * (ycnc + dir)));
                    Graphic.StopPath();
                }
                lastWasBlack = false;
            }
        }
Exemplo n.º 8
0
 public HSLColor(Color color)
 {
     RGB = color;
     H = (byte)((color.GetHue() / 360.0f) * 255);
     S = (byte)(color.GetSaturation() * 255);
     L = (byte)(color.GetBrightness() * 255);
 }
Exemplo n.º 9
0
        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;
            }
        }
Exemplo n.º 10
0
        public Bitmap HistogramEqualiztion(Bitmap image)
        {
            Bitmap bmp = image;

            long[] GrHst = new long[256]; long HstValue = 0;
            long[] GrSum = new long[256]; long SumValue = 0;
            for (int row = 0; row < bmp.Height; row++)
            {
                for (int col = 0; col < bmp.Width; col++)
                {
                    HstValue = (long)(255 * bmp.GetPixel(col, row).GetBrightness());
                    GrHst[HstValue]++;
                }
            }
            for (int level = 0; level < 255; level++)
            {
                SumValue    += GrHst[level];
                GrSum[level] = SumValue;
            }
            for (int row = 0; row < bmp.Height; row++)
            {
                for (int col = 0; col < bmp.Width; col++)
                {
                    System.Drawing.Color clr = bmp.GetPixel(col, row);
                    HstValue = (long)(255 * clr.GetBrightness());
                    HstValue = (long)(255f / (bmp.Width * bmp.Height) * GrSum[HstValue] - HstValue);
                    int R = (int)Math.Min(255, clr.R + HstValue / 3); //.299
                    int G = (int)Math.Min(255, clr.G + HstValue / 3); //.587
                    int B = (int)Math.Min(255, clr.B + HstValue / 3); //.112
                    bmp.SetPixel(col, row, System.Drawing.Color.FromArgb(Math.Max(R, 0), Math.Max(G, 0), Math.Max(B, 0)));
                }
            }
            return(bmp);
        }
Exemplo n.º 11
0
 /// <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();
 }
Exemplo n.º 12
0
        /// <summary>
        /// Sets and returns average brightness level (from fully black at 0.0 to fully white at 1.0) of this
        /// WBImage
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns>Average brightness level of given bitmap image</returns>
        public float CalculateAverageBrightness(Bitmap image)
        {
            // Brightness value to be summed and averaged
            float averageBrightness = 0;

            // Get log of width and height of image; to be used when looping over pixels to
            // increase efficiency
            // (Rather than looping over every pixel, using the log will allow taking a sample
            //  of only pixels on every log(width)th column and log(height)th row)
            int widthLog  = Convert.ToInt32(Math.Log(image.Width));
            int heightLog = Convert.ToInt32(Math.Log(image.Height));

            // Loop over image's pixels (taking only the logged sample as described above)
            for (int x = 0; x < image.Width; x += widthLog)
            {
                for (int y = 0; y < image.Height; y += heightLog)
                {
                    // For every sampled pixel, get the color value of the pixel and add its brightness to
                    // the running sum
                    System.Drawing.Color pixelColor = image.GetPixel(x, y);
                    averageBrightness += pixelColor.GetBrightness();
                }
            }

            // Divide summed brightness by the number of pixels sampled to get the average
            averageBrightness /= (image.Width / widthLog) * (image.Height / heightLog);

            return(averageBrightness);
        }
Exemplo n.º 13
0
 private static Color GetFullContrastColor(Color color)
 {
     return
         color.GetBrightness() > BrightnessThreshold
             ? Color.Black
             : Color.White;
 }
Exemplo n.º 14
0
        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);
        }
        private void binarization(Bitmap imgSrc)
        {
           
            int px; double br;
            double threshold = 0.5;
            
            for (int row = 0; row < height - 1; row++)
            {
                for (int col = 0; col < width - 1; col++)
                {
                    pixel = imgSrc.GetPixel(col, row);
                    px = pixel.ToArgb();
                    br = pixel.GetBrightness();
                    if (pixel.GetBrightness() < threshold)
                    {

                        GreyImage[col, row] = 0;

                    }
                    else
                    {

                        GreyImage[col, row] = 1;
                    }

                }
            }
        }
Exemplo n.º 16
0
 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();
 }
Exemplo n.º 17
0
        public async Task ASCII()
        {
            Bitmap image = await GetImage();

            if (image == null)
            {
                await ReplyAsync("Please provide an image attachment.");

                return;
            }

            string pixelCharacters = DefaultASCII;

            List <char> chars = new List <char>(image.Height * image.Width + image.Height);

            for (int y = 0; y < image.Height; y++)
            {
                for (int x = 0; x < image.Width; x++)
                {
                    System.Drawing.Color pixel = image.GetPixel(x, y);
                    int normalizedGrayscale    = (int)(pixel.GetBrightness() * (pixelCharacters.Length - 1));
                    chars.Add(pixelCharacters[normalizedGrayscale]);
                }
                chars.Add('\n');
            }

            // Find way to not have the memory being copied around
            using (MemoryStream memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(new string(chars.ToArray()))))
            {
                await Context.Message.Channel.SendFileAsync(memoryStream, $"${Context.Message.Attachments.First().Filename}ASCII.txt");
            }

            image.Dispose();
        }
Exemplo n.º 18
0
 public bool IsOldStar(Color pixelColor)
 {
     return ((pixelColor.GetHue() >= 150) &&
         (pixelColor.GetHue() <= 258) &&
         (pixelColor.GetSaturation() >= 0.10) &&
         (pixelColor.GetBrightness() <= 0.90));
 }
Exemplo n.º 19
0
        public async Task Grayscale()
        {
            Bitmap image = await GetImage();

            if (image == null)
            {
                await ReplyAsync("Please provide an image attachment.");

                return;
            }

            Bitmap gray = new Bitmap(image.Width, image.Height);

            for (int y = 0; y < image.Height; y++)
            {
                for (int x = 0; x < image.Width; x++)
                {
                    System.Drawing.Color pixel = image.GetPixel(x, y);
                    byte brightness            = (byte)(pixel.GetBrightness() * 255);
                    gray.SetPixel(x, y, System.Drawing.Color.FromArgb(pixel.A, brightness, brightness, brightness));
                }
            }

            using (MemoryStream stream = new MemoryStream())
            {
                gray.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                stream.Position = 0;
                await Context.Channel.SendFileAsync(stream, $"{Context.Message.Attachments.First().Filename}-grayscale.png");
            }

            image.Dispose();
            gray.Dispose();
        }
        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);
        }
 public HslColor(Color color)
 {
   _alpha = color.A;
   _hue = color.GetHue();
   _saturation = color.GetSaturation();
   _lightness = color.GetBrightness();
   _isEmpty = false;
 }
Exemplo n.º 22
0
        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;
            }
        }
Exemplo n.º 23
0
        private float ColorDiff(System.Drawing.Color c0, System.Drawing.Color c1)
        {
            var rDiff = Math.Abs(c0.R - c1.R);
            var gDiff = Math.Abs(c0.G - c1.G);
            var bDiff = Math.Abs(c0.B - c1.B);

            //Console.WriteLine(rDiff+" "+ gDiff +" "+bDiff);
            return(Math.Abs(c0.GetBrightness() - c1.GetBrightness()));
        }
Exemplo n.º 24
0
 public static HSV ToHsv(this System.Drawing.Color c)
 {
     return(new HSV()
     {
         H = c.GetHue(),
         S = c.GetSaturation(),
         V = c.GetBrightness(),
     });
 }
Exemplo n.º 25
0
        /// <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);
        }
Exemplo n.º 26
0
        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));
        }
Exemplo n.º 27
0
        //
        /// <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;
        }
Exemplo n.º 28
0
 /// <summary>
 /// Method to add/sum two colors.
 /// </summary>
 /// <param name="hitColor"></param>
 /// <param name="tintColor"></param>
 /// <returns></returns>
 public static Color AddColor(Color hitColor, Color tintColor)
 {
     float brightness = tintColor.GetBrightness();
     var result = Color.FromArgb(
             (int)Cap((int)((1 - brightness) * hitColor.R) + CapMin(tintColor.R - 20, 0) * 255 / 205, 255),
             (int)Cap((int)((1 - brightness) * hitColor.G) + CapMin(tintColor.G - 20, 0) * 255 / 205, 255),
             (int)Cap((int)((1 - brightness) * hitColor.B) + CapMin(tintColor.B - 20, 0) * 255 / 205, 255)
         );
     return result;
 }
Exemplo n.º 29
0
		int CompareColorByBrightness(Color c1, Color c2)
		{
			float h1 = c1.GetBrightness();
			float h2 = c2.GetBrightness();
			if (h1 < h2)
				return -1;
			if (h1 > h2)
				return 1;
			return 0;
		}
Exemplo n.º 30
0
        private void SynchronizeButtonContainer()
        {
            if (UserPreferencesManager.Instance.UserPreferences == null)
            {
                return;
            }

            debugRenderControl.ClearColor          = UserPreferencesManager.Instance.UserPreferences.DebugRenderClearColor;
            debugRenderControl.FSAA                = UserPreferencesManager.Instance.UserPreferences.DebugRenderFSAA;
            debugRenderControl.IsPerspective       = UserPreferencesManager.Instance.UserPreferences.DebugRender3DView;
            debugRenderControl.ShowLineNormals     = (UserPreferencesManager.Instance.UserPreferences.DebugRenderShowNormals == ShowNormalsMode.Lines);
            debugRenderControl.ShowTriangleNormals = (UserPreferencesManager.Instance.UserPreferences.DebugRenderShowNormals == ShowNormalsMode.Triangles);
            debugRenderControl.ShowAnnotations     = UserPreferencesManager.Instance.UserPreferences.DebugRenderAnnotations;
            debugRenderControl.ShowGrid            = UserPreferencesManager.Instance.UserPreferences.DebugRenderShowGrid;

            DisableUIEvents = true;

            rdrButtonContainer.GetToggleAnnotations().Checked = UserPreferencesManager.Instance.UserPreferences.DebugRenderAnnotations;
            rdrButtonContainer.GetToggleAnnotations().Text    = rdrButtonContainer.GetToggleAnnotations().Checked ? "Annotations (All)" : "Annotations (None)";

            rdrButtonContainer.GetToggleDimensions().Checked = UserPreferencesManager.Instance.UserPreferences.DebugRender3DView;
            rdrButtonContainer.GetToggleDimensions().Text    = rdrButtonContainer.GetToggleDimensions().Checked ? "3D" : "2D";

            rdrButtonContainer.GetToggleFSAA().Checked = UserPreferencesManager.Instance.UserPreferences.DebugRenderFSAA;
            rdrButtonContainer.GetToggleFSAA().Text    = rdrButtonContainer.GetToggleFSAA().Checked ? "+ FSAA" : "- FSAA";

            System.Drawing.Color clearColor = System.Drawing.Color.FromArgb(UserPreferencesManager.Instance.UserPreferences.DebugRenderClearColor.R,
                                                                            UserPreferencesManager.Instance.UserPreferences.DebugRenderClearColor.G,
                                                                            UserPreferencesManager.Instance.UserPreferences.DebugRenderClearColor.B);
            rdrButtonContainer.GetClearColor().BackColor = clearColor;
            rdrButtonContainer.GetClearColor().ForeColor = clearColor.GetBrightness() >= 0.5 ? System.Drawing.Color.Black : System.Drawing.Color.White;

            switch (UserPreferencesManager.Instance.UserPreferences.DebugRenderShowNormals)
            {
            case ShowNormalsMode.None:
                rdrButtonContainer.GetCycleNormalsButton().Text = "Normals (None)";
                break;

            case ShowNormalsMode.Lines:
                rdrButtonContainer.GetCycleNormalsButton().Text = "Normals (Lines)";
                break;

            case ShowNormalsMode.Triangles:
                rdrButtonContainer.GetCycleNormalsButton().Text = "Normals (Triangles)";
                break;

            default:
                break;
            }

            rdrButtonContainer.GetToggleGrid().Checked = UserPreferencesManager.Instance.UserPreferences.DebugRenderShowGrid;
            rdrButtonContainer.GetToggleGrid().Text    = rdrButtonContainer.GetToggleGrid().Checked ? "+ Grid" : "- Grid";

            DisableUIEvents = false;
        }
Exemplo n.º 31
0
 /// <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);
 }
Exemplo n.º 32
0
 /// <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);
     }
 }
Exemplo n.º 33
0
		int CompareColorByBrightness(Color c1, Color c2)
		{
			// bug, using float causes the sort to go into infinite loop in release,
			// but only when run as standalone. If started from Visual Studio it works correct in release.
			// other work around is to move float h1 and h2 out of the method
			double h1 = c1.GetBrightness();
			double h2 = c2.GetBrightness();
			if (h1 < h2)
				return -1;
			if (h1 > h2)
				return 1;
			return 0;
		}
Exemplo n.º 34
0
        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};
        }
Exemplo n.º 35
0
        /// <summary>
        /// Gets the character for pixel based on its brightness.
        /// </summary>
        /// <param name="pixel">The pixel.</param>
        /// <returns>
        /// An ascii representation of the pixel
        /// </returns>
        public override string GetCharForPixel(Color pixel)
        {
            // Convert the transparent background to black
            if (pixel.A == 0)
                pixel = Color.White;

            // 0.0 is black 1.0 is white
            float brightness = 1f - pixel.GetBrightness();
            int i = MAP.Length - (int)(brightness * MAP.Length);
            if (i > MAP.Length - 1)
                i = MAP.Length - 1;

            return MAP.Substring(i,1);
        }
Exemplo n.º 36
0
        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();
        }
Exemplo n.º 37
0
		static Color ColorForEffect(EffectType t, Color orig)
		{
			switch (t)
			{
				case EffectType.Black:
					return Color.FromArgb(orig.A, Color.Black);
				case EffectType.Desaturated:
					var lum = (int)(255 * orig.GetBrightness());
					return Color.FromArgb(orig.A, lum, lum, lum);
				default:
				case EffectType.None:
					return orig;
			}
		}
Exemplo n.º 38
0
        /// <summary>
        /// Gets the type of the contrast color.
        /// </summary>
        /// <param name="color">The color.</param>
        /// <param name="colorType">Type of the color.</param>
        /// <returns></returns>
        private static EdgeColorType GetContrastColorType(Color color, EdgeColorType colorType)
        {
            Debug.Assert(colorType == EdgeColorType.Contrast || colorType == EdgeColorType.EnhancedContrast);
            if (color.GetBrightness() > BrightnessThreshold)
            {
                return colorType == EdgeColorType.Contrast
                    ? EdgeColorType.DarkerThanSurface
                    : EdgeColorType.DarkerDarkerThanSurface;
            }

            return colorType == EdgeColorType.Contrast
                ? EdgeColorType.LighterThanSurface
                : EdgeColorType.LighterLighterThanSurface;
        }
Exemplo n.º 39
0
        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;
            }
        }
Exemplo n.º 40
0
        /// <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);
            }
        }
Exemplo n.º 41
0
        //-------------------------------------------------------------------------------------------------------
        //Матрица яркости из изображения (диапазон 0..1)
        public static RealMatrix GetBrightnessMatrixFromBitmap(Bitmap bitmap)
        {
            int        sizeX            = bitmap.Width;
            int        sizeY            = bitmap.Height;
            RealMatrix brightnessMatrix = new RealMatrix(sizeY, sizeX);

            for (int x = 0; x < sizeX; x++)
            {
                for (int y = 0; y < sizeY; y++)
                {
                    System.Drawing.Color pixelColor = bitmap.GetPixel(x, y);
                    double brightness = pixelColor.GetBrightness();
                    brightnessMatrix[y, x] = brightness;
                }
            }
            return(brightnessMatrix);
        }
Exemplo n.º 42
0
        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());
            }
        }
Exemplo n.º 43
0
        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();
        }
Exemplo n.º 44
0
        /* create a new binary image of specified filename from specified file */
        public static void buildBinImage(Bitmap image, string newFile)
        {
            Bitmap newImage = new Bitmap(image.Width, image.Height);
            Color color = new Color();

            for (int y = 0; y < image.Height; y++){
                for (int x = 0; x < image.Width; x++){
                    color = image.GetPixel(x, y);
                    if ( color.GetBrightness() < 0.5 ){
                        newImage.SetPixel(x, y, Color.Black);
                    }
                    else{
                        newImage.SetPixel(x, y, Color.White);
                    }
                }
            }
            newImage.Save(newFile);
        }
Exemplo n.º 45
0
        /// <summary>
        ///     Ccompares two colors by brightness and returns an indication of their relative sort order.
        /// </summary>
        /// <param name="x">A color to compare to y.</param>
        /// <param name="y">A color to compare to x.</param>
        public static int Brightness(Color x, Color y)
        {
            float v1;
            float v2;
            int result;

            v1 = x.GetBrightness();
            v2 = y.GetBrightness();

            if (v1 < v2)
                result = -1;
            else if (v1 > v2)
                result = 1;
            else
                result = 0;

            return result;
        }
Exemplo n.º 46
0
        /* create a new binary image of specified filename from specified file */
        public static void buildBinImage(Bitmap image, float threshold, string fileName)
        {
            Bitmap newImage = new Bitmap(image.Width, image.Height);
            Color color = new Color();

            for (int y = 0; y < image.Height; y++){
                for (int x = 0; x < image.Width; x++){
                    color = image.GetPixel(x, y);
                    if ( color.GetBrightness() > threshold ){
                        newImage.SetPixel(x, y, Color.White);
                    }
                    else{
                        newImage.SetPixel(x, y, Color.Black);
                    }
                }
            }
            newImage.Save(fileName, ImageFormat.Bmp);
        }
Exemplo n.º 47
0
 public static void DrawDesignTimeSelection(Graphics g, Rectangle r, Color backColor, Color border, int penWidth)
 {
     if (r.Width <= 0 || r.Height <= 0)
         return;
     if (!backColor.IsEmpty && backColor != Color.Transparent)
     {
         if ((double)backColor.GetBrightness() < 0.5)
             border = System.Windows.Forms.ControlPaint.Light(backColor);
         else
             border = System.Windows.Forms.ControlPaint.Dark(backColor);
     }
     using (Pen pen = new Pen(border, penWidth))
     {
         pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
         r.Width--;
         r.Height--;
         g.DrawRectangle(pen, r);
     }
 }
Exemplo n.º 48
0
        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();
        }
Exemplo n.º 49
0
        /* build cell table */
        public static Cell[,] buildCellTable(Bitmap image, float threshold)
        {
            Cell[,] cellArr = new Cell[image.Width/2, image.Height/3];
            Color color = new Color();

            for (int majr = 0; majr < cellArr.GetLength(1); majr++){
                for (int majc = 0; majc < cellArr.GetLength(0); majc++){
                    cellArr[majc, majr] = new Cell();
                    for (int minr = 0; minr < 3; minr++){
                        for (int minc = 0; minc < 2; minc++){
                            color = image.GetPixel((2 * majc) + minc, (3 * majr) + minr);
                            if (color.GetBrightness() <= threshold){
                                cellArr[majc, majr].addDot((3 * minc) + minr + 1);
                            }
                        }
                    }
                }
            }
            return cellArr;
        }
Exemplo n.º 50
0
        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);
        }
Exemplo n.º 51
0
        protected override void OnDrawWindow(System.Windows.Forms.PaintEventArgs e, Skybound.VisualTips.VisualTip tip, Skybound.VisualTips.Rendering.VisualTipLayout layout)
        {
            System.Drawing.Drawing2D.GraphicsPath graphicsPath1;

            System.Drawing.Rectangle rectangle1 = layout.WindowBounds;
            bool flag = BackgroundEffect == Skybound.VisualTips.Rendering.VisualTipOfficeBackgroundEffect.Glass;

            if (RoundCorners)
            {
                graphicsPath1 = Skybound.VisualTips.Rendering.VisualTipRenderer.CreateRoundRectPath(rectangle1, Skybound.VisualTips.Rendering.VisualTipRenderer.LayeredWindowsSupported ? 5 : 7, Skybound.VisualTips.Rendering.VisualTipRenderer.BorderCorners.All);
            }
            else
            {
                graphicsPath1 = new System.Drawing.Drawing2D.GraphicsPath();
                graphicsPath1.AddRectangle(new System.Drawing.Rectangle(rectangle1.Location, rectangle1.Size - (new System.Drawing.Size(1, 1))));
            }
            using (System.Drawing.Brush brush = new System.Drawing.Drawing2D.LinearGradientBrush(rectangle1, BackColor, BackColorGradient, (float)(GradientAngle + (flag ? 180 : 0)), false))
            {
                e.Graphics.FillPath(brush, graphicsPath1);
            }
            if (flag)
            {
                System.Drawing.Color color3 = BackColor;
                int i1 = (int)((1.0F - ((1.0F - color3.GetBrightness()) * 0.75F)) * 255.0F);
                System.Drawing.Color color1 = System.Drawing.Color.FromArgb(i1, i1, i1);
                using (System.Drawing.Drawing2D.LinearGradientBrush linearGradientBrush = new System.Drawing.Drawing2D.LinearGradientBrush(rectangle1, System.Drawing.Color.FromArgb(128, color1), System.Drawing.Color.FromArgb(0, color1), System.Drawing.Drawing2D.LinearGradientMode.Vertical))
                    using (System.Drawing.Drawing2D.GraphicsPath graphicsPath2 = CreateGlarePath(rectangle1, Skybound.VisualTips.Rendering.VisualTipRenderer.LayeredWindowsSupported ? 5 : 7))
                    {
                        e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        e.Graphics.FillPath(linearGradientBrush, graphicsPath2);
                        e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.Default;
                    }
            }
            using (System.Drawing.Pen pen1 = new System.Drawing.Pen(BorderColor))
            {
                if (Skybound.VisualTips.Rendering.VisualTipRenderer.LayeredWindowsSupported)
                {
                    e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                }
                else
                {
                    pen1.Alignment = System.Drawing.Drawing2D.PenAlignment.Center;
                }
                e.Graphics.DrawPath(pen1, graphicsPath1);
                if (Skybound.VisualTips.Rendering.VisualTipRenderer.LayeredWindowsSupported)
                {
                    e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.Default;
                }
            }
            if (HasFooter(tip))
            {
                System.Drawing.Rectangle rectangle2 = layout.GetElementBounds(Skybound.VisualTips.Rendering.VisualTipRenderElement.FooterImage);
                int i2 = rectangle2.Top - 6;
                System.Drawing.Color color4 = BackColorGradient;
                System.Drawing.Color color5 = BackColorGradient;
                System.Drawing.Color color6 = BackColorGradient;
                System.Drawing.Color color2 = System.Drawing.Color.FromArgb((int)((float)color4.R * 0.9F), (int)((float)color5.G * 0.9F), (int)((float)color6.B * 0.9F));
                using (System.Drawing.Pen pen2 = new System.Drawing.Pen(color2))
                {
                    e.Graphics.DrawLine(pen2, rectangle1.X + 5, i2, rectangle1.Right - 6, i2);
                    pen2.Color = System.Windows.Forms.ControlPaint.Light(BackColor);
                    e.Graphics.DrawLine(pen2, rectangle1.X + 5, i2 + 1, rectangle1.Right - 6, i2 + 1);
                }
            }
        }
Exemplo n.º 52
0
        /// <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);
        }
Exemplo n.º 53
0
        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     = "ステータス:完了";
        }
Exemplo n.º 54
0
 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);
 }
Exemplo n.º 55
0
    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;
    }
Exemplo n.º 56
0
        /// <summary>
        /// Add the ROWSxCOLS number of buttons and setup their initial settings.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnPageLoaded(object sender, RoutedEventArgs e)
        {
            Grid grid = new Grid();

            grid.Background = new SolidColorBrush(System.Windows.Media.Color.FromScRgb(1.0f, 0.0f, 0.0f, 0.0f));

            // Resize the window to the number of buttons
            Application.Current.Windows[0].Height = ROWS * BUTTON_SIZE;
            Application.Current.Windows[0].Width  = COLS * BUTTON_SIZE;

            // Allow dropping of images onto this grid
            grid.Drop     += OnImageDrop;
            grid.AllowDrop = true;

            // Setup the columns and rows
            for (int i = 0; i < COLS; i++)
            {
                grid.ColumnDefinitions.Add(new ColumnDefinition());
            }

            for (int i = 0; i < ROWS; i++)
            {
                grid.RowDefinitions.Add(new RowDefinition());
            }

            for (int y = 0; y < ROWS; y++)
            {
                for (int x = 0; x < COLS; x++)
                {
                    System.Windows.Media.Color tempColor     = System.Windows.Media.Color.FromScRgb(1.0f, x / (float)COLS, y / (float)ROWS, 0.5f);
                    System.Drawing.Color       tempDrawColor = System.Drawing.Color.FromArgb(tempColor.A, tempColor.R, tempColor.G, tempColor.B);

                    // Create the label for the button that changes between white and black
                    // for contrast with the buttons background color
                    Label buttonLabel = new Label
                    {
                        Content    = String.Format("{0},{1}", x, y),
                        Foreground = new SolidColorBrush(tempDrawColor.GetBrightness() < 0.5 ? System.Windows.Media.Color.FromScRgb(1.0f, 1.0f, 1.0f, 1.0f) : System.Windows.Media.Color.FromScRgb(1.0f, 0.0f, 0.0f, 0.0f)),
                        FontSize   = 12,
                    };

                    Button button = new Button
                    {
                        Tag                 = new Vector2(x, y),
                        ClickMode           = ClickMode.Press,
                        Cursor              = Cursors.Hand,
                        Content             = buttonLabel,
                        BorderThickness     = new Thickness(0.0),
                        SnapsToDevicePixels = true,
                    };

                    // Copy the color code when clicked
                    button.Click += OnColorClicked;

                    UpdateButtonStyle(button, tempColor);

                    // Unused buttons are hidden which is all buttons at the start
                    button.Visibility = Visibility.Hidden;

                    Grid.SetColumn(button, x);
                    Grid.SetRow(button, y);

                    grid.Children.Add(button);
                }
            }

            (sender as Page).Content = grid;
        }
Exemplo n.º 57
0
        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);
        }
Exemplo n.º 58
0
        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);
        }
Exemplo n.º 59
0
        public static void ProcessStyles(Bitmap source, ref Bitmap Disabled, ref Bitmap Shadowed)
        {
            Color shadowColor = SystemColors.ControlDarkDark;

            //First we need to ensure the image is valid...
            if (source != null)
            {
                //Prepare two copies of the image, mostly to ensure equal size.
                System.Drawing.Bitmap disabled = (Bitmap)source.Clone();
                System.Drawing.Bitmap shadow   = (System.Drawing.Bitmap)source.Clone();
                try
                {
                    //We start the loop vertically first so it goes from top to
                    //bottom, the internal loop is horizontal to ensure
                    //an order of right->left and top->bottom respectively.
                    //Loop through it vertically
                    for (int y = 0; y < shadow.Height; y++)
                    {
                        //Loop through it horizontally
                        for (int x = 0; x < shadow.Width; x++)
                        {
                            //There's really no special logic to processing these.
                            //I just messed around with this until I liked it.
                            System.Drawing.Color mC = source.GetPixel(x, y);
                            int avg   = 255 - (int)((float)Math.Min(Math.Min(mC.R, mC.B), mC.G) + (float)Math.Max(Math.Max(mC.R, mC.B), mC.G)) / 2;
                            int alpha = (int)(((float)mC.A * ((float)avg / 255)) / 255 * 128) + ((mC.A == 0) ? 0 : 64);
                            shadow.SetPixel(x, y, System.Drawing.Color.FromArgb(alpha, (int)((float)mC.R / 255F * (float)shadowColor.R), (int)((float)mC.G / 255F * (float)shadowColor.G), (int)((float)mC.B / 255F * (float)shadowColor.B)));
                            disabled.SetPixel(x, y, System.Drawing.Color.FromArgb((int)((mC.A == 0) ? 0 : (128 - (mC.GetBrightness() * 128))), mC.R, mC.G, mC.B));
                        }
                    }
                }
                catch (System.Exception e) { System.Console.WriteLine(e.ToString()); }
                Shadowed = shadow;
                Disabled = disabled;
            }
        }
Exemplo n.º 60
0
 public int DeltaB(Dye other)
 {
     return((int)(100 * (other.Color.GetBrightness() / Color.GetBrightness()) + .5));
     // ImageMagick interprets 100 as unchanged (100%), 200 as twice as bright 50 as half as bright
 }