Exemplo n.º 1
0
        /// <summary>
        /// Корректирует центр первой ячейки ответа
        /// </summary>
        /// <param name="image">ссылка на изображение</param>
        public void CorrectFirstCellCenter(Bitmap image)
        {
            //увеличиваем ячейки
            int maxWidth  = _cellswidth + Convert.ToInt16(_cellswidth * 2 / 3);
            int maxHeigth = _cellsheight + Convert.ToInt16(_cellsheight * 2 / 3);

            _cells.ReMeasure(_firstcelldistances, _intercentresdistx, maxWidth, maxHeigth);
            BitmapData  data        = image.LockBits(_cells[0].Rect, ImageLockMode.ReadWrite, image.PixelFormat);
            BlobCounter blobCounter = new BlobCounter();

            Invert invertfilter = new Invert();

            invertfilter.ApplyInPlace(data);
            blobCounter.ProcessImage(data);

            Blob[] blobs = blobCounter.GetObjectsInformation();
            int    maxar = 0;
            int    b     = 0;

            for (int i = 0; i < blobs.Count(); i++)
            {
                if (blobs[i].Area > maxar)
                {
                    maxar = blobs[i].Area; b = i;
                }
            }
            invertfilter.ApplyInPlace(data);
            image.UnlockBits(data);


            System.Drawing.Point p = new System.Drawing.Point(_cells[0].CenterOfGravity.X - ((maxWidth / 2) - Convert.ToInt16(blobs[b].CenterOfGravity.X)), _cells[0].CenterOfGravity.Y - ((maxHeigth / 2) - Convert.ToInt16(blobs[b].CenterOfGravity.Y)));
            _cells.ReMeasure(p, _intercentresdistx, _cellswidth, _cellsheight);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Добавляет несколько несколько ячеек в ответ начиная с первой
        /// </summary>
        /// <param name="image">Ссылка ни изображение</param>
        /// <param name="CellsCount">Количество ячеек для добавления в ответ</param>
        /// <param name="FirstCellDistanses">Коллекция дистанций между первой ячейкой и маркерами</param>
        /// <param name="intercentresdistX">Расстояние между центрами ячеек</param>
        /// <param name="Width">Длина ячеек</param>
        /// <param name="Height">Высота ячеек</param>
        public void IntelligentAdd(Bitmap image, int CellsCount, Distances FirstCellDistanses, int intercentresdistX, int Width, int Height)
        {
            int maxslice = intercentresdistX / 2;

            //находим первую доступную дистанцию
            Distance d         = FirstCellDistanses.FindOneGood();
            int      maxWidth  = Width + Convert.ToInt16(Width / 2);
            int      maxHeigth = Height + Convert.ToInt16(Height / 2);

            //увеличиваем ячейки

            this.Add(image, CellsCount, FirstCellDistanses, intercentresdistX, maxWidth, maxHeigth);


            BitmapData  data        = image.LockBits(_cells[0].Rect, ImageLockMode.ReadWrite, image.PixelFormat);
            BlobCounter blobCounter = new BlobCounter();

            Invert invertfilter = new Invert();

            invertfilter.ApplyInPlace(data);
            blobCounter.ProcessImage(data);

            Blob[] blobs = blobCounter.GetObjectsInformation();
            if (blobs.Length != 0)
            {
                int maxar = 0;
                int b     = 0;
                for (int i = 0; i < blobs.Count(); i++)
                {
                    if (blobs[i].Area > maxar)
                    {
                        maxar = blobs[i].Area; b = i;
                    }
                }
                invertfilter.ApplyInPlace(data);


                System.Drawing.Point p = new System.Drawing.Point(_cells[0].CenterOfGravity.X - ((maxWidth / 2) - Convert.ToInt16(blobs[b].CenterOfGravity.X)), _cells[0].CenterOfGravity.Y - ((maxHeigth / 2) - Convert.ToInt16(blobs[b].CenterOfGravity.Y)));
                if (Math.Abs(_cells[0].CenterOfGravity.Y - p.Y) <= maxslice)
                {
                    this.ReMeasure(p, intercentresdistX, Width, Height);
                }
                else
                {
                    this.ReMeasure(_cells[0].CenterOfGravity, intercentresdistX, Width, Height);
                }
            }
            image.UnlockBits(data);
        }
Exemplo n.º 3
0
        public static Image Invert(this Image imagex)
        {
            var image  = AForge.Imaging.Image.Clone(new Bitmap(imagex), PixelFormat.Format24bppRgb);
            var filter = new Invert();

            filter.ApplyInPlace(image);

            var fastImage = new LockBitmap(image);

            fastImage.LockBits();
            var vert = 0;

            while (vert < fastImage.Height)
            {
                var hor = 0;
                while (hor < fastImage.Width)
                {
                    var color = fastImage.GetPixel(hor, vert);
                    if (color.R >= 90)
                    {
                        fastImage.SetPixel(hor, vert, Color.White);
                    }

                    hor++;
                }
                vert++;
            }
            fastImage.UnlockBits();



            return(fastImage.GetBitmap());
        }
Exemplo n.º 4
0
        public Bitmap Invert(Bitmap imgEdgeDetected)
        {
            Invert inv = new Invert();

            inv.ApplyInPlace(imgEdgeDetected);
            return(imgEdgeDetected);
        }
Exemplo n.º 5
0
        private Image <Gray, Byte> prepareImg2(System.Drawing.Image img, int threshold, bool invertImg)
        {
            Image <Gray, Byte> GrayImg = new Image <Gray, byte>((Bitmap)img);


            EmgImgProcssing = new ImageProcessing_Emgu();


            // create the filter
            BradleyLocalThresholding filter2 = new BradleyLocalThresholding();

            // apply the filter
            filter2.ApplyInPlace(GrayImg.Bitmap);

            GrayImg = GrayImg.Erode(1).Dilate(5).Erode(1);

            // create filter
            Invert filter3 = new Invert();

            // apply the filter
            filter3.ApplyInPlace(GrayImg.Bitmap);


            return(GrayImg);
        }
Exemplo n.º 6
0
        public IScanImage Scan(ISource source, ScannerOptions options)
        {
            var image = new Bitmap(source.Take());

            // create grayscale filter (BT709)
            var filter     = new Grayscale(0.2125, 0.7154, 0.0721);
            var mBinarized = filter.Apply(image);

            // Binarize Picture.
            var bin = new Threshold(options.Threshold);

            bin.ApplyInPlace(mBinarized);

            // create filter
            var inv = new Invert();

            inv.ApplyInPlace(mBinarized);

            // create an instance of blob counter algorithm
            var bc = new BlobCounter {
                ObjectsOrder = ObjectsOrder.XY
            };

            bc.ProcessImage(mBinarized);
            var blobsRect = bc.GetObjectsRectangles();

            var b = Order(blobsRect);

            return(new ScanImage(image, b));
        }
Exemplo n.º 7
0
        internal ExamImage(Bitmap im)
        {
            lock (syob)
            {
                orgimg   = im;
                this.img = AForge.Imaging.Image.Clone(im, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            }
            //img = im;
            Invert inv = new Invert();

            inv.ApplyInPlace(img);
            //BlobsFiltering bf = new BlobsFiltering(new MixFiltering());
            //bf.ApplyInPlace(img);
            BlobCounter bc = new BlobCounter();

            bc.BlobsFilter          = new SyncRectangleFilter();
            bc.FilterBlobs          = true;
            bc.CoupledSizeFiltering = true;
            bc.ProcessImage(img);
            syncboxs = bc.GetObjects(img, true);

            if (isFlip())
            {
                img.RotateFlip(RotateFlipType.Rotate180FlipNone);
                bc.ProcessImage(img);
                syncboxs = bc.GetObjects(img, true);
            }

            bc.BlobsFilter = new AnswerFilter();
            bc.ProcessImage(img);
            answers = bc.GetObjects(img, true);


            stuNumber = getNumber();
        }
Exemplo n.º 8
0
        public Bitmap GetNegativeImage()
        {
            Bitmap newImage = (Bitmap)image.Clone();
            Invert filter   = new Invert();

            filter.ApplyInPlace(newImage);
            return(newImage);
        }
Exemplo n.º 9
0
        /*
         * 1- gray scale transform;
         * */
        public void ToGray(ref Bitmap image)
        {
            image = (Bitmap)ResizeImage((System.Drawing.Image)image);

            // Create a blank bitmap with the same dimensions
            Bitmap imageGray = new Bitmap(image);


            Median medianFilter = new Median();

            // apply the filter
            medianFilter.ApplyInPlace(image);


            // create grayscale filter (BT709)
            Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721);

            // apply the filter
            image = filter.Apply(imageGray);

            // create filter
            Invert invertFilter = new Invert();

            // apply the filter
            invertFilter.ApplyInPlace(image);

            // create filter
            OtsuThreshold filterOtsuThreshold = new OtsuThreshold();

            // apply the filter
            filterOtsuThreshold.ApplyInPlace(image);
            // check threshold value
            int t = filterOtsuThreshold.ThresholdValue;

            /*
             * // create and configure the filter
             * FillHoles holesFilter = new FillHoles();
             * holesFilter.MaxHoleHeight = 2;
             * holesFilter.MaxHoleWidth = 2;
             * holesFilter.CoupledSizeFiltering = false;
             * // apply the filter
             * Bitmap result = holesFilter.Apply(image);
             *
             *
             * BinaryDilatation3x3 bd = new BinaryDilatation3x3();
             * bd.ApplyInPlace(image);
             * bd.ApplyInPlace(image);
             *
             * // create filter
             * BlobsFiltering filterBlobsFiltering = new BlobsFiltering();
             * // configure filter
             * filterBlobsFiltering.CoupledSizeFiltering = true;
             * filterBlobsFiltering.MinWidth = 5;
             * filterBlobsFiltering.MinHeight = 5;
             * // apply the filter
             * filterBlobsFiltering.ApplyInPlace(image);
             */
        }
        private bool IsLicensePlate(Bitmap plate)
        {
            invert.ApplyInPlace(plate);
            plateBlobsFiltering.ApplyInPlace(plate);
            plateBlobCounter.ProcessImage(plate);
            Blob[] blobs = plateBlobCounter.GetObjectsInformation();
            int    chars = blobs.Length;

            return(5 <= chars && chars <= 9);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Creates a comic rendered copy of the input image.
        /// </summary>
        public override Bitmap Render(Bitmap sourceImage)
        {
            GrayscaleToRGB convertColor = new GrayscaleToRGB();

            if (sourceImage.PixelFormat == PixelFormat.Format8bppIndexed)
            {
                sourceImage = convertColor.Apply(sourceImage);
            }

            BilateralBlur blur  = new BilateralBlur(3, 0.1);
            Bitmap        comic = blur.Apply(sourceImage);

            // Edges
            Bitmap            grayscale = Grayscale.CommonAlgorithms.Y.Apply(comic);
            SobelEdgeDetector sobelEdge = new SobelEdgeDetector();

            sobelEdge.ScaleIntensity = true;
            Bitmap edgeLayer = sobelEdge.Apply(grayscale);

            edgeLayer = convertColor.Apply(edgeLayer);

            Invert invertEdge = new Invert();

            invertEdge.ApplyInPlace(edgeLayer);

            HSLLinear edgeLinear = new HSLLinear();

            edgeLinear.InLuminance.Min = 0;
            edgeLinear.InLuminance.Max = 0.8;
            edgeLinear.ApplyInPlace(edgeLayer);


            // highlights
            Bitmap     highlightLayer      = invertEdge.Apply(edgeLayer);
            Dilatation highlightDilitation = new Dilatation();

            highlightDilitation.ApplyInPlace(highlightLayer);

            BrightnessCorrection highlightBright = new BrightnessCorrection(-0.35);

            highlightBright.ApplyInPlace(highlightLayer);
            ColorDodge highlightBlend = new ColorDodge(highlightLayer);

            highlightBlend.ApplyInPlace(comic);


            // Merge edges with working layer
            Multiply multEdge = new Multiply(edgeLayer);

            multEdge.ApplyInPlace(comic);


            return(comic);
        }
Exemplo n.º 12
0
        private static Bitmap PreProcess(Bitmap bmp)
        {
            Grayscale gfilter = new Grayscale(0.2125, 0.7154, 0.0721);
            Invert    ifilter = new Invert();
            BradleyLocalThresholding thfilter = new BradleyLocalThresholding();

            bmp = gfilter.Apply(bmp);
            thfilter.ApplyInPlace(bmp);
            ifilter.ApplyInPlace(bmp);
            return(bmp);
        }
Exemplo n.º 13
0
        // source
        // http://stackoverflow.com/questions/35980717/why-doesnt-aforge-net-blobcounter-getobjectsinformation-detect-objects
        private Bitmap PreProcess(Bitmap bmp)
        {
            //Those are AForge filters "using Aforge.Imaging.Filters;"
            Grayscale gfilter = new Grayscale(0.2125, 0.7154, 0.0721);
            Invert    ifilter = new Invert();
            BradleyLocalThresholding thfilter = new BradleyLocalThresholding();

            bmp = gfilter.Apply(bmp);
            thfilter.ApplyInPlace(bmp);
            ifilter.ApplyInPlace(bmp);
            return(bmp);
        }
Exemplo n.º 14
0
        public static void Invert(Bitmap image)
        {
            var      col      = image.GetPixel(100, 200);
            Graphics graphics = Graphics.FromImage(image);

            graphics.FillEllipse(new SolidBrush(Color.Yellow), 100, 200, DinoCircleRadius, DinoCircleRadius);
            if (col.R > 50 && col.G > 50 && col.B > 50)
            {
                Invert filter = new Invert();
                filter.ApplyInPlace(image);
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// This method binarize dnd dilate image.
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        private Bitmap BinarizeAndDilationWithMedian(Bitmap image)
        {
            int[,] kernel =
            {
                { -2, -1, 0 },
                { -1,  1, 1 },
                {  0,  1, 2 }
            };
            // create filter
            Convolution Convolution = new Convolution(kernel);

            // apply the filter
            Convolution.ApplyInPlace(image);

            var bmp8bpp = Grayscale.CommonAlgorithms.BT709.Apply(image);

            Invert invert = new Invert();

            invert.ApplyInPlace(bmp8bpp);

            Dilatation dilatation = new Dilatation();

            dilatation.ApplyInPlace(bmp8bpp);

            invert.ApplyInPlace(bmp8bpp);

            Median median = new Median();

            median.ApplyInPlace(bmp8bpp);

            Closing closing = new Closing();

            closing.ApplyInPlace(bmp8bpp);

            OtsuThreshold OtsuThreshold = new OtsuThreshold();

            OtsuThreshold.ApplyInPlace(bmp8bpp);
            //bmp8bpp.Save(@"C:\Users\Maor\Desktop\mode\BinarizeAndDilationWithMedian.jpeg");
            return(bmp8bpp);
        }
Exemplo n.º 16
0
        private Bitmap ProcessImageDiference(Bitmap lastimg, Bitmap openingFilterImg)
        {
            // create filter
            Difference filter = new Difference(openingFilterImg);
            // apply the filter
            Bitmap resultImage = filter.Apply(lastimg);
            // create filter
            Invert filter2 = new Invert();

            // apply the filter
            filter2.ApplyInPlace(resultImage);
            return(resultImage);
        }
Exemplo n.º 17
0
        public static List <Bitmap> CutImages(Bitmap bitmap, Action <Bitmap> act = null)
        {
            Bitmap sourceBitmap = bitmap;
            Bitmap targetBitmap = (Bitmap)sourceBitmap.Clone();

            if (!AForge.Imaging.Image.IsGrayscale(targetBitmap))
            {
                targetBitmap = AForge.Imaging.Image.Clone(targetBitmap, PixelFormat.Format24bppRgb);
                targetBitmap = Grayscale.CommonAlgorithms.BT709.Apply(targetBitmap);
            }

            if (act == null)
            {
                targetBitmap = new Threshold(50).Apply(targetBitmap);
                Invert filter = new Invert();
                filter.ApplyInPlace(targetBitmap);

                BlobsFiltering bolbsfilter = new BlobsFiltering();
                bolbsfilter.CoupledSizeFiltering = true;
                bolbsfilter.MinWidth             = 4;
                bolbsfilter.MinHeight            = 4;
                bolbsfilter.ApplyInPlace(targetBitmap);

                Closing binary = new Closing();
                targetBitmap = binary.Apply(targetBitmap);
                filter.ApplyInPlace(targetBitmap);
            }
            else
            {
                act(targetBitmap);
            }


            var bit1 = Crop_Y(targetBitmap);
            var bit2 = Crop_X(bit1);

            return(ToResizeAndCenterIt(bit2));
        }
Exemplo n.º 18
0
        public void ProcessImage(Bitmap input_image)
        {
            lock (balanceLock)
            {
                int       side     = Math.Min(input_image.Height, input_image.Width);
                Rectangle cropRect = new Rectangle(0, 0, side, side);                                                               // this is square that represents feed from camera
                g.DrawImage(input_image, new Rectangle(0, 0, input_image.Width, input_image.Height), cropRect, GraphicsUnit.Pixel); // place it on original bitmap

                // set new processed
                if (processed != null)
                {
                    processed.Dispose();
                }

                //  Конвертируем изображение в градации серого
                processed = grayFilter.Apply(AForge.Imaging.UnmanagedImage.FromManagedImage(original));
                //  Пороговый фильтр применяем. Величина порога берётся из настроек, и меняется на форме
                threshldFilter.PixelBrightnessDifferenceLimit = ThresholdValue;
                threshldFilter.ApplyInPlace(processed);
                InvertFilter.ApplyInPlace(processed);
                Blober.ProcessImage(processed);
                AForge.Imaging.Blob[] blobs = Blober.GetObjectsInformation();
                BlobCount = blobs.Length;

                if (blobs.Length > 0)
                {
                    var BiggestBlob = blobs[0];
                    Recongnised = true;
                    Blober.ExtractBlobsImage(processed, BiggestBlob, false);
                    processed = BiggestBlob.Image;
                    AForge.Point mc = BiggestBlob.CenterOfGravity;
                    AForge.Point ic = new AForge.Point((float)BiggestBlob.Image.Width / 2, (float)BiggestBlob.Image.Height / 2);
                    AngleRad = (ic.Y - mc.Y) / (ic.X - mc.X);
                    Angle    = (float)(Math.Atan(AngleRad) * 180 / Math.PI);
                }
                else
                {
                    // TODO make arrengaments for No blobs case
                    Recongnised = false;
                    Angle       = 0;
                    AngleRad    = -1;
                }

                if (number != null)
                {
                    number.Dispose();
                }
                number = processed.ToManagedImage();
            }
        }
Exemplo n.º 19
0
        private void ProcessImage()
        {
            m_selectedBlobs.Clear();
            pictureBox1.Controls.Clear();
            pictureBox1.Image = null;

            if (m_original != null)
            {
                m_original.Dispose();
            }
            if (m_binarized != null)
            {
                m_binarized.Dispose();
            }

            m_original = new Bitmap(txtFile.Text);

            // create grayscale filter (BT709)
            Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721);

            m_binarized = filter.Apply(m_original);

            // Binarize Picture.
            Threshold bin = new Threshold((int)txtBinThershold.Value);

            bin.ApplyInPlace(m_binarized);

            // create filter
            Invert inv = new Invert();

            inv.ApplyInPlace(m_binarized);

            // create an instance of blob counter algorithm
            BlobCounter bc = new BlobCounter();

            bc.ObjectsOrder = ObjectsOrder.XY;
            bc.ProcessImage(m_binarized);
            Rectangle[] blobsRect = bc.GetObjectsRectangles();
            Dictionary <int, List <Rectangle> > orderedBlobs = ReorderBlobs(blobsRect);

            foreach (KeyValuePair <int, List <Rectangle> > orderedBlob in orderedBlobs)
            {
                orderedBlob.Value.ForEach(r => AddBlobPanel(orderedBlob.Key, r));
            }

            pictureBox1.Image = chkShowBinarize.Checked ? m_binarized : m_original;

            pictureBox1.Invalidate();
        }
Exemplo n.º 20
0
        public static Bitmap invert(Bitmap source) // 반전
        {
            Bitmap tmp = (Bitmap)source;           // 중요! 한번 이미지 처리가 끝난 비트맵 source 는 clone 함수로 보내기 전에 다시 한번 (Bitmap) 처리 해줘야함, 이유는 잘 모르겠음

            // convert to 24 bits per pixel
            source = imageProcess.Clone(tmp, PixelFormat.Format24bppRgb);
            // delete old image
            tmp.Dispose();

            Invert invertfilter = new Invert();

            invertfilter.ApplyInPlace(source);

            return(source);
        }
        private void SetInvertC(object obj)
        {
            Bitmap bmp = null;

            try
            {
                bmp = (Bitmap)Images.Instance.CurrentBitmap.Clone();
            }
            catch { }
            Bitmap bmpselected = null;

            try
            {
                bmpselected = (Bitmap)Images.Instance.SelectedBitmap.Clone();
            }
            catch { }
            if (partarea == true)
            {
                if (bmpselected != null)
                {
                    invertfilter.ApplyInPlace(bmpselected);
                    Graphics newImage = Graphics.FromImage(bmp);
                    newImage.DrawImage(bmpselected, (int)SelectedPoints.selectPointForEfX, (int)SelectedPoints.selectPointForEfY, bmpselected.Width, bmpselected.Height);
                }
            }
            else
            {
                if (bmp != null)
                {
                    invertfilter.ApplyInPlace(bmp);
                }
            }
            Images.Instance.CurrentBitmap = bmp;
            Images.Instance.NotifyImages();
            this.Temporary = bmp;
        }
Exemplo n.º 22
0
        void InvertToolStripMenuItemClick(object sender, EventArgs e)
        {
            //jika gambar kosong/null maka akan mengembalikan nilai kosong/null
            if (gambar == null)
            {
                return;
            }
            //membuat filter dari inisiasi class Invert() pada objek invert
            Invert invert = new Invert( );

            //clone variable gambar pada variable gambar2
            gambar2 = (Bitmap)gambar.Clone();
            //aplikasikan filter objek invert pada gambar2
            invert.ApplyInPlace(gambar2);
            //tampilkan hasil gambar2 yang sudah diaplikasikan filter pada pictureBox2
            pictureBox2.Image = gambar2;
        }
Exemplo n.º 23
0
        public Bitmap Negative(Bitmap image)
        {
            //for (int x = 0; x < image.Width; x++)
            //{
            //    for (int y = 0; y < image.Height; y++)
            //    {
            //        Color color = image.GetPixel(x, y);
            //        color = Color.FromArgb(255 - color.R, 255-color.G, 255-color.B);
            //        image.SetPixel(x, y, color);
            //        //pixelColor = Color.FromArgb(greyColor, greyColor, greyColor);

            //    }
            //}
            Invert invertFilter = new Invert();

            // apply the filter
            invertFilter.ApplyInPlace(image);
            return(image);
        }
Exemplo n.º 24
0
        void Finalvideo_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            Bitmap image = (Bitmap)eventArgs.Frame.Clone();

            pictureBox1.Image = image;


            if (radioButton1.Checked)
            {
                Bitmap image1 = (Bitmap)eventArgs.Frame.Clone();

                Grayscale filter    = new Grayscale(0.2125, 0.7154, 0.0721);
                Bitmap    grayImage = filter.Apply(image1);
                Threshold filter2   = new Threshold(100);
                filter2.ApplyInPlace(grayImage);
                Invert filter3 = new Invert();
                filter3.ApplyInPlace(grayImage);

                pictureBox2.Image = grayImage;
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Creates a comic rendered copy of the input image.
        /// </summary>
        public override Bitmap Render(Bitmap sourceImage)
        {
            Bitmap sketchImage = AForge.Imaging.Image.Clone(sourceImage);

            GrayscaleY convertGray = new GrayscaleY();

            // Blur
            GaussianBlur filterBlur = new GaussianBlur();

            filterBlur.Sigma = this.PencilTipSize;
            filterBlur.Size  = this.PencilTipSize;
            Bitmap overLayer = filterBlur.Apply(sketchImage);

            // Invert over layer
            Invert sketchInvert = new Invert();

            sketchInvert.ApplyInPlace(overLayer);

            BrightnessCorrection filterBrightness = new BrightnessCorrection(-this.Range * 0.01);

            filterBrightness.ApplyInPlace(overLayer);

            ContrastCorrection filterContrast = new ContrastCorrection(1 - (-this.Range * 0.01));

            filterContrast.ApplyInPlace(overLayer);

            // Convert to grayscale
            sketchImage = convertGray.Apply(sketchImage);
            overLayer   = convertGray.Apply(overLayer);

            // Dodge blending for the win!
            ColorDodge dodgeBlend = new ColorDodge(overLayer);

            dodgeBlend.ApplyInPlace(sketchImage);

            return(sketchImage);
        }
        public static Bitmap PrepareForObjectDetection(this System.Drawing.Image bmpOriginalImage, int whiteLevel, bool overrideWhite)
        {
            Bitmap bmp = (Bitmap)bmpOriginalImage.Clone();

            ColorFiltering colorFilter = new ColorFiltering();

            int white = whiteLevel;

            if (!overrideWhite)
            {
                white = PreprocessingHelper.GetWhiteLevel(bmp);
            }

            colorFilter.Red              = new IntRange(0, white / 3);
            colorFilter.Green            = new IntRange(0, white / 3);
            colorFilter.Blue             = new IntRange(0, white / 3);
            colorFilter.FillOutsideRange = true;

            colorFilter.FillColor = new RGB(Color.White);
            colorFilter.ApplyInPlace(bmp);

            ExtractChannel extract_channel = new ExtractChannel(0);

            bmp = extract_channel.Apply(bmp);

            Invert invert = new Invert();

            invert.ApplyInPlace(bmp);

            Threshold threshholdFilter = new Threshold(10);

            threshholdFilter.ApplyInPlace(bmp);

            bmp = bmp.Clone(new Rectangle(0, 0, bmp.Width, bmp.Height), PixelFormat.Format24bppRgb);

            return(bmp);
        }
Exemplo n.º 27
0
        private void etal1btn_Click(object sender, EventArgs e)
        {
            Grayscale grayfilter = new Grayscale(0.2125, 0.7154, 0.0721);

            // применяем фильтр
            grayImage = grayfilter.Apply((Bitmap)vebpb.Image);
            //выводим на пичербокс
            //pictureBox1.Image = grayImage;

            mainImage = grayImage.Clone(
                new Rectangle(0, 0, grayImage.Width, grayImage.Height),
                System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
            Bitmap Image24 = grayImage.Clone(
                new Rectangle(0, 0, grayImage.Width, grayImage.Height),
                System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            Bitmap Image8 = grayImage.Clone(
                new Rectangle(0, 0, grayImage.Width, grayImage.Height),
                System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
            ProcessingImage pi     = new ProcessingImage();
            OtsuThreshold   filter = new OtsuThreshold();

            // apply the filter
            filter.ApplyInPlace(Image8);

            // check threshold value
            Invert filter1 = new Invert();

            ////// apply the filter
            filter1.ApplyInPlace(Image8);


            //изменить блобкаунтер
            BlobCounter bc = new BlobCounter();

            // process binary image
            bc.ProcessImage(Image8);

            Rectangle[] rects = bc.GetObjectsRectangles();

            Bitmap bp      = new Bitmap(Image8);
            Bitmap final   = new Bitmap(Image24.Width, Image24.Height);
            Bitmap bp8     = new Bitmap(Image8);
            int    xCenter = Image8.Width / 2;
            int    yCenter = Image8.Height / 2;

            Bitmap tempImage = grayImage.Clone(
                new Rectangle(0, 0, grayImage.Width, grayImage.Height),
                System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            Graphics g = Graphics.FromImage(tempImage);  //получаю объект графики из битмап

            SolidBrush b = new SolidBrush(Color.Black);  //кисть для заливки

            bp  = tempImage.Clone(rects[0], System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            bp8 = Image8.Clone(rects[0], System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
            g.FillRectangle(b, new Rectangle(0, 0, tempImage.Width, tempImage.Height)); //заполняю
            for (int x = 0; x < bp8.Width; x++)
            {
                for (int y = 0; y < bp8.Height; y++)
                {
                    if (bp8.GetPixel(x, y).R == 0)
                    {
                        bp.SetPixel(x, y, Color.Black);
                    }
                }
            }
            int shiftX = xCenter - rects[0].Width / 2;
            int shiftY = yCenter - rects[0].Height / 2;

            g.DrawImage(bp, shiftX, shiftY, rects[0].Width, rects[0].Height);
            //etalonimages.Add(tempImage);

            foreach (PictureBox pb in etalonpanel.Controls.OfType <PictureBox>())
            {
                if (pb.Image == null)
                {
                    pb.Image = tempImage;
                    break;
                }
            }
        }
Exemplo n.º 28
0
        private void recognize_Click(object sender, EventArgs e)
        {
            label15.Text = "";
            if (etalonimages.Count == 0)
            {
                foreach (PictureBox pb in etalonpanel.Controls.OfType <PictureBox>())
                {
                    if (pb.Image != null)
                    {
                        etalonimages.Add((Bitmap)pb.Image);
                    }
                }

                //чтение из файлов параметров

                ContourEtalCentr = ReadFromFile("ContourCentr.txt", 18);
                HullEtalCentr    = ReadFromFile("HullCentr.txt", 28);

                ContourEtalMedoid = ReadFromFile("ContourMed.txt", 18);
                HullEtalMedoid    = ReadFromFile("HullCentrMed.txt", 28);
            }
            Grayscale grayfilter = new Grayscale(0.2125, 0.7154, 0.0721);

            // применяем фильтр
            grayImage = grayfilter.Apply((Bitmap)vebpb.Image);
            //выводим на пичербокс
            //pictureBox1.Image = grayImage;

            //Application.Idle -= GetVideo;
            mainImage = grayImage.Clone(
                new Rectangle(0, 0, grayImage.Width, grayImage.Height),
                System.Drawing.Imaging.PixelFormat.Format8bppIndexed);


            //медианный фильтр для шумов границ размытых объектов
            Median filter1 = new Median();

            filter1.ApplyInPlace(mainImage);


            OtsuThreshold filter = new OtsuThreshold();

            // apply the filter

            filter.ApplyInPlace(mainImage);
            // check threshold value
            Invert filter2 = new Invert();

            // apply the filter
            filter2.ApplyInPlace(mainImage);


            // исправили потомучто надо
            //RecursiveBlobCounter bc = new RecursiveBlobCounter();
            BlobCounter bc = new BlobCounter();

            // process binary image
            bc.ProcessImage(mainImage);

            Rectangle[] rects = bc.GetObjectsRectangles();

            List <Bitmap> images         = new List <Bitmap>();
            List <Bitmap> imagesWithEdge = new List <Bitmap>();
            Bitmap        bp;
            int           i = 0;

            foreach (Rectangle rect in rects)
            {
                images.Add(new Bitmap(mainImage.Width, mainImage.Height));
                Graphics   g = Graphics.FromImage(images[i]);                               //получаю объект графики из битмап
                SolidBrush b = new SolidBrush(Color.Black);                                 //кисть для заливки
                g.FillRectangle(b, new Rectangle(0, 0, images[i].Width, images[i].Height)); //заполняю
                bp = mainImage.Clone(rects[i], System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
                g.DrawImage(bp, rects[i].X, rects[i].Y, rects[i].Width, rects[i].Height);
                i++;
            }

            //List <List<System.Drawing.Point>> convexHull = new List<List<System.Drawing.Point>>();
            ProcessingImage             pi      = new ProcessingImage();
            QuickHull                   qh      = new QuickHull();
            Contur                      cont    = new Contur();
            List <System.Drawing.Point> localPt = new List <System.Drawing.Point>();

            foreach (Bitmap img in images)
            {
                //формирование выпуклой оболочки
                localPt = pi.GetPoints(img);
                List <System.Drawing.Point> ConvexHullLocal = qh.quickHull(localPt);
                ConvexHullLocal = qh.DeleteAnglePoints(ConvexHullLocal);
                convexHull.Add(ConvexHullLocal);
                //и контура
                List <System.Drawing.Point> ConturLocal = cont.kontur(img);
                ConturLocal = cont.DeleteAnglePoints(ConturLocal);
                edgePoint.Add(ConturLocal);
                imagesWithEdge.Add(img.Clone(new Rectangle(0, 0, img.Width, img.Height), System.Drawing.Imaging.PixelFormat.Format32bppRgb));
            }

            int hullimagenum = 0;

            foreach (PictureBox pb in Hullpanel.Controls)
            {
                if (hullimagenum < images.Count)
                {
                    pb.Image = images[hullimagenum];
                }
                hullimagenum++;
            }


            //выделение векторов признаков
            List <Primary>  marks                 = new List <Primary>();
            List <double[]> objectMarksHull       = new List <double[]>();
            List <double[]> objectMarksContur     = new List <double[]>();
            List <double[]> etallMarksCentrHull   = new List <double[]>();
            List <double[]> etallMarksCentrContur = new List <double[]>();
            List <double[]> etallMarksMedHull     = new List <double[]>();
            List <double[]> etallMarksMedContur   = new List <double[]>();

            for (i = 0; i < images.Count; i++)
            {
                marks.Add(new Primary(images[i], edgePoint[i], convexHull[i]));
                objectMarksContur.Add(marks[i].Contour());
                objectMarksHull.Add(marks[i].Convex());
            }

            //Отрисовка выпуклой оболочки
            for (i = 0; i < convexHull.Count; i++)
            {
                Graphics gr1 = Graphics.FromImage(images[i]);
                List <System.Drawing.Point> pt = new List <System.Drawing.Point>(convexHull[i]);
                for (int j = 0; j < pt.Count; j++)
                {
                    qh.PutPixel(gr1, Color.Red, pt[j].X, pt[j].Y, 255);
                }
                gr1 = Graphics.FromImage(imagesWithEdge[i]);
                List <System.Drawing.Point> pt1 = new List <System.Drawing.Point>(edgePoint[i]);
                for (int j = 0; j < pt1.Count; j++)
                {
                    cont.PutPixel(gr1, Color.Red, pt1[j].X, pt1[j].Y, 255);
                }
            }

            int contourimagenum = 0;

            foreach (PictureBox pb in Contourpanel.Controls)
            {
                if (contourimagenum < imagesWithEdge.Count)
                {
                    pb.Image = imagesWithEdge[contourimagenum];
                }
                contourimagenum++;
            }

            //int hullimagenum = 0;
            //foreach (PictureBox pb in Hullpanel.Controls)
            //{
            //    if (hullimagenum < images.Count)
            //        pb.Image = images[hullimagenum];
            //    hullimagenum++;
            //}


            for (int j = 0; j < etalonimages.Count; j++)
            {
                etallMarksCentrContur.Add(ContourEtalCentr[j]);
                etallMarksMedContur.Add(ContourEtalMedoid[j]);
                etallMarksCentrHull.Add(HullEtalCentr[j]);
                etallMarksMedHull.Add(HullEtalMedoid[j]);
            }


            for (int l = 0; l < images.Count; l++)
            {
                compareobjects(objectMarksHull,
                               objectMarksContur,
                               etallMarksCentrContur,
                               etallMarksMedContur,
                               etallMarksCentrHull,
                               etallMarksMedHull, l);
            }


            images.Clear();
            convexHull.Clear();
            edgePoint.Clear();
            imagesWithEdge.Clear();
            marks.Clear();
            //contourMarks.Clear();
            i = 0;
        }
        private void process_image(PictureBox box, bool toinvert)
        {
            Bitmap original = (Bitmap)Bitmap.FromFile(_fname);

            original.Save("C:\\users\\alberto geniola\\desktop\\dbg\\original_" + toinvert + ".bmp");

            // Setup the Blob counter
            BlobCounter blobCounter = new BlobCounter();

            blobCounter.BackgroundThreshold  = Color.FromArgb(10, 10, 10);
            blobCounter.FilterBlobs          = true;
            blobCounter.CoupledSizeFiltering = false;
            blobCounter.MinHeight            = minHeight;
            blobCounter.MinWidth             = minWidth;

            List <Blob> blobs = new List <Blob>();

            // Button scanning
            // Apply the grayscale. This is needed for AForge's filters
            using (Bitmap grey_scaled = Grayscale.CommonAlgorithms.BT709.Apply(original))
            {
                // Invert the image if requested
                if (toinvert)
                {
                    Invert invert = new Invert();
                    invert.ApplyInPlace(grey_scaled);
                }

                using (Bitmap t1 = new Threshold(64).Apply(grey_scaled))
                {
                    using (var tmp = new Bitmap(t1.Width, t1.Height))
                    {
                        using (Graphics g = Graphics.FromImage(tmp))
                        {
                            g.DrawImage(t1, 0, 0);
                        }

                        tmp.Save("C:\\users\\alberto geniola\\desktop\\dbg\\filtered_" + toinvert + ".bmp");

                        // The blob counter will analyze the bitmap looking for shapes
                        blobCounter.ProcessImage(tmp);
                        var tmparr = blobCounter.GetObjectsInformation();
                        blobs.AddRange(tmparr);

                        for (int i = 0, n = tmparr.Length; i < n; i++)
                        {
                            List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);
                            if (edgePoints.Count > 1)
                            {
                                IntPoint p0, p1;
                                PointsCloud.GetBoundingRectangle(edgePoints, out p0, out p1);
                                var r = new Rectangle(p0.X, p0.Y, p1.X - p0.X, p1.Y - p0.Y);

                                // Skip any shape representing the border of the whole window ( +10px padding)
                                if (r.Width >= (original.Width - 10))
                                {
                                    continue;
                                }

                                using (var g = Graphics.FromImage(tmp))
                                {
                                    g.DrawRectangle(_marker, r);
                                }
                            }
                        }

                        tmp.Save("C:\\users\\alberto geniola\\desktop\\dbg\\processed_" + toinvert + ".bmp");
                    }
                }

                using (Bitmap t2 = new SISThreshold().Apply(grey_scaled))
                {
                    using (var tmp = new Bitmap(t2.Width, t2.Height))
                    {
                        using (Graphics g = Graphics.FromImage(tmp))
                        {
                            g.DrawImage(t2, 0, 0);
                        }
                        tmp.Save("C:\\users\\alberto geniola\\desktop\\dbg\\t2_" + toinvert + ".bmp");
                        // The blob counter will analyze the bitmap looking for shapes
                        blobCounter.ProcessImage(tmp);
                        var tmparr = blobCounter.GetObjectsInformation();
                        blobs.AddRange(tmparr);

                        for (int i = 0, n = tmparr.Length; i < n; i++)
                        {
                            List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);
                            if (edgePoints.Count > 1)
                            {
                                IntPoint p0, p1;
                                PointsCloud.GetBoundingRectangle(edgePoints, out p0, out p1);
                                var r = new Rectangle(p0.X, p0.Y, p1.X - p0.X, p1.Y - p0.Y);

                                // Skip any shape representing the border of the whole window ( +10px padding)
                                if (r.Width >= (original.Width - 10))
                                {
                                    continue;
                                }

                                using (var g = Graphics.FromImage(tmp))
                                {
                                    g.DrawRectangle(_marker, r);
                                }
                            }
                        }

                        tmp.Save("C:\\users\\alberto geniola\\desktop\\dbg\\t1_" + toinvert + ".bmp");
                    }
                }
            }


            Bitmap test = (Bitmap)original.Clone();

            // Let's analyze every single shape
            for (int i = 0, n = blobs.Count; i < n; i++)
            {
                List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);
                if (edgePoints.Count > 1)
                {
                    IntPoint p0, p1;
                    PointsCloud.GetBoundingRectangle(edgePoints, out p0, out p1);
                    var r = new Rectangle(p0.X, p0.Y, p1.X - p0.X, p1.Y - p0.Y);

                    // Skip any shape representing the border of the whole window ( +10px padding)
                    if (r.Width >= (original.Width - 10))
                    {
                        continue;
                    }

                    using (var g = Graphics.FromImage(test))
                    {
                        g.DrawRectangle(_marker, r);
                    }

                    // This is most-likely a button!
                    // Crop the image and pass it to the OCR engine for text recognition
                    using (Bitmap button = new Bitmap(r.Width, r.Height))
                    {
                        // Scan the original shape
                        String txt = null;
                        using (var g1 = Graphics.FromImage(button))
                        {
                            g1.DrawImage(original, 0, 0, r, GraphicsUnit.Pixel);
                        }

                        // Process OCR on that image
                        txt = scanButton(button);

                        if (String.IsNullOrEmpty(txt))
                        {
                            using (Bitmap tmp = Grayscale.CommonAlgorithms.BT709.Apply(button))
                            {
                                if (toinvert)
                                {
                                    new Invert().ApplyInPlace(tmp);
                                }

                                new SISThreshold().ApplyInPlace(tmp);
                                txt = scanButton(tmp);
                            }
                        }

                        // If still nothing is found, repeat the analysis with the second version of the filter
                        if (String.IsNullOrEmpty(txt))
                        {
                            using (Bitmap tmp = Grayscale.CommonAlgorithms.BT709.Apply(button))
                            {
                                if (toinvert)
                                {
                                    new Invert().ApplyInPlace(tmp);
                                }
                                new Threshold(64).ApplyInPlace(tmp);
                                txt = scanButton(tmp);
                            }
                        }

                        if (!String.IsNullOrEmpty(txt))
                        {
                            using (var g = Graphics.FromImage(test))
                            {
                                int    SPACING = 5;
                                double angle   = 45 * 2 * Math.PI / 360; // 45 degrees to radiants
                                for (int x = 0; x < r.Width; x += SPACING)
                                {
                                    PointF start = new PointF(r.X + x, r.Y);
                                    PointF end   = new PointF((float)(r.X + x + r.Height * Math.Tan(angle)), r.Y + r.Height);
                                    if (end.X > (r.X + r.Width))
                                    {
                                        // Calculate midpoint
                                        var delta = end.X - r.Width;
                                        end.X = r.X + r.Width;
                                        end.Y = r.Y + (float)(Math.Tan(angle) * r.Width) - x;

                                        // Draw the overflow line
                                        g.DrawLine(_marker2, r.X, end.Y, delta, r.Y + r.Height);
                                    }

                                    g.DrawLine(_marker2, start, end);
                                }

                                g.FillRectangle(_b, r);
                                var dim = g.MeasureString(txt.Trim(), _f);
                                g.DrawString(txt.Trim().ToUpper(), _f, _b2, r.X + (r.Width - dim.Width) / 2, r.Y + (r.Height - dim.Height) / 2);
                            }
                        }

                        test.Save("C:\\users\\alberto geniola\\desktop\\dbg\\processed_" + toinvert + ".bmp");

                        /*
                         * // At this point we should have a result. Add it to list if it does not overlap any UIAutomated element
                         * UIControlCandidate t = new UIControlCandidate();
                         * t.PositionWindowRelative = r;
                         * var winLoc = w.WindowLocation;
                         * t.PositionScreenRelative = new Rectangle(r.X + winLoc.X, r.Y + winLoc.Y, r.Width, r.Height);
                         * t.Text = txt;
                         * t.Score = policy.RankElement(t);
                         *
                         * // If the item falls into the same area of a UI element, ignore it.
                         * bool overlaps = false;
                         * foreach (var el in res)
                         * {
                         *  if (el.AutoElementRef != null && el.PositionScreenRelative.IntersectsWith(t.PositionScreenRelative))
                         *  {
                         *      overlaps = true;
                         *      break;
                         *  }
                         * }
                         * if (!overlaps)
                         *  res.Add(t);
                         */
                    }
                }

                box.Image = test;
            }
        }
Exemplo n.º 30
0
        void SensorFrameReady(AllFramesReadyEventArgs e)
        {
            // if the window is displayed, show the depth buffer image
            Bitmap mask = null;

            using (DepthImageFrame frame = e.OpenDepthImageFrame())
            {
                if (frame != null)
                {
                    _depthBitmap = CreateBitMapFromDepthFrame(frame);
                    ColorFiltering filter = new ColorFiltering();
                    filter.Red   = new IntRange(50, 150);
                    filter.Green = new IntRange(200, 255);
                    filter.Blue  = new IntRange(150, 255);
                    // apply the filter
                    _depthBitmap = AForge.Imaging.Image.Clone(_depthBitmap, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    mask         = filter.Apply(_depthBitmap);


                    Grayscale gray = new Grayscale(0.7, 0.3, 0.1);
                    mask = gray.Apply(mask);

                    Threshold threshold = new Threshold(100);
                    threshold.ApplyInPlace(mask);

                    Invert invert = new Invert();
                    invert.ApplyInPlace(mask);
                }
            }

            using (ColorImageFrame frame = e.OpenColorImageFrame())
            {
                if (frame != null)
                {
                    _bitmap = _drawBitmap = ImageToBitmap(frame);
                    if (mask != null)
                    {
                        ApplyMask subtract = new ApplyMask(mask);
                        _bitmap = subtract.Apply(_bitmap);
                    }

                    HSLFiltering hsl = new HSLFiltering(new IntRange(330, 30), new Range(0.5f, 1), new Range(0.1f, 1));
                    hsl.ApplyInPlace(_bitmap);

                    Grayscale gray = new Grayscale(1, 0.8, 0.8);
                    _bitmap = gray.Apply(_bitmap);


                    Mean meanFilter = new Mean();
                    meanFilter.ApplyInPlace(_bitmap);


                    BlobsFiltering blob = new BlobsFiltering();
                    blob.CoupledSizeFiltering = false;
                    blob.MinHeight            = 15;
                    blob.MinWidth             = blob.MinHeight;
                    blob.MaxHeight            = blob.MaxWidth = 300;
                    blob.ApplyInPlace(_bitmap);

                    // locate objects using blob counter
                    BlobCounter blobCounter = new BlobCounter();
                    blobCounter.ProcessImage(_bitmap);
                    Blob[] blobs = blobCounter.GetObjectsInformation();

                    Pen redPen    = new Pen(Color.Red, 2);
                    Pen greenPen  = new Pen(Color.Green, 2);
                    Pen purplePen = new Pen(Color.OrangeRed, 3);
                    Pen pen;
                    // check each object and draw circle around objects, which
                    // are recognized as circles
                    int    maxBlob     = -1;
                    double maxFullness = -1;
                    for (int i = 0, n = blobs.Length; i < n; i++)
                    {
                        float hw_ratio = (float)(blobs[i].Rectangle.Height) / blobs[i].Rectangle.Width;

                        if (hw_ratio > 0.65 && hw_ratio < 1.5 && blobs[i].Area > 200 && blobs[i].Fullness > 0.35)
                        {
                            if (blobs[i].Area > maxFullness)
                            {
                                maxBlob     = i;
                                maxFullness = blobs[i].Area;
                            }
                        }
                    }

                    System.Console.WriteLine("MAX BLOB: " + maxBlob.ToString());


                    //draw to screen!
                    Grayscale gray2 = new Grayscale(0.2125, 0.7154, 0.072);
                    _drawBitmap = gray2.Apply(_drawBitmap);
                    _drawBitmap = AForge.Imaging.Image.Clone(_drawBitmap, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                    Graphics g = Graphics.FromImage(_drawBitmap);

                    AForge.Point ballPos = new AForge.Point(-1, -1);
                    if (maxBlob >= 0)
                    {
                        ballPos = blobs[maxBlob].CenterOfGravity;
                    }
                    game.DrawGridAndScore(g, ballPos);

                    for (int i = 0, n = blobs.Length; i < n; i++)
                    {
                        float hw_ratio = (float)(blobs[i].Rectangle.Height) / blobs[i].Rectangle.Width;

                        if (hw_ratio > 0.65 && hw_ratio < 1.5 && blobs[i].Area > 200 && blobs[i].Fullness > 0.35)
                        {
                            AForge.Point center = blobs[i].CenterOfGravity;
                            if (maxBlob == i)
                            {
                                pen = purplePen;
                            }
                            else if (blobs[i].Fullness > 0.35)
                            {
                                continue;//pen = greenPen;
                            }
                            else
                            {
                                continue;// pen = redPen;
                            }
                            float radius = blobs[i].Rectangle.Width / 2;
                            g.DrawEllipse(pen,
                                          (int)(center.X - radius),
                                          (int)(center.Y - radius),
                                          (int)(radius * 2),
                                          (int)(radius * 2));
                            //g.DrawString(hw_ratio.ToString(), new Font("Arial", 16), new SolidBrush(Color.Yellow),
                            //   new System.Drawing.Point((int)center.X, (int)center.Y));
                        }
                    }

                    redPen.Dispose();
                    greenPen.Dispose();
                    purplePen.Dispose();
                    g.Dispose();

                    if (game.hasWon)
                    {
                        if (player == game.winningPlayer)
                        {
                            label1.Text = "You Won!!! Congrats :)";
                        }
                        else
                        {
                            label1.Text = "You Lost... :(";
                        }
                    }

                    this.Refresh();
                }
            }
        }