Example #1
0
        public void IsCircleTest( )
        {
            Assert.AreEqual(true, shapeChecker.IsCircle(idealCicle));
            Assert.AreEqual(true, shapeChecker.IsCircle(distorredCircle));

            Assert.AreEqual(false, shapeChecker.IsCircle(square1));
            Assert.AreEqual(false, shapeChecker.IsCircle(square2));
            Assert.AreEqual(false, shapeChecker.IsCircle(square3));
            Assert.AreEqual(false, shapeChecker.IsCircle(rectangle));

            Assert.AreEqual(false, shapeChecker.IsCircle(triangle1));
            Assert.AreEqual(false, shapeChecker.IsCircle(equilateralTriangle));
            Assert.AreEqual(false, shapeChecker.IsCircle(isoscelesTriangle));
            Assert.AreEqual(false, shapeChecker.IsCircle(rectangledTriangle));
        }
        public bool getCirlces(Bitmap bitmap)
        {
            bool isCirclePresent = false;

            BlobCounter blobCounter = new BlobCounter();

            blobCounter.ProcessImage(bitmap);
            Blob[] blobs = blobCounter.GetObjectsInformation();

            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

            shapeChecker.RelativeDistortionLimit = 00.15F;

            for (int i = 0, n = blobs.Length; i < n; i++)
            {
                List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);

                AForge.Point center;
                float        radius;


                if (shapeChecker.IsCircle(edgePoints))
                {
                    isCirclePresent = true;
                }
            }



            return(isCirclePresent);
        }
        public List <int> GetLocationOfAllCircles(Bitmap bit)
        {
            Bitmap     bits         = edgedetection(bit);
            List <int> circleX      = new List <int>();
            List <int> circleY      = new List <int>();
            List <int> circleRadius = new List <int>();

            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

            BlobCounter blobCounter = new BlobCounter();

            blobCounter.ProcessImage(bits);
            Blob[] blobs = blobCounter.GetObjectsInformation();


            shapeChecker.RelativeDistortionLimit = 0.03f;

            for (int i = 0, n = blobs.Length; i < n; i++)
            {
                //Console.WriteLine("blob info is  " + blobs[i].CenterOfGravity);


                List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);

                AForge.Point center;
                float        radius;


                // Console.WriteLine("The count is" + edgePoints.Count);



                if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                {
                    circleX.Add((int)center.X);
                    circleY.Add((int)center.Y);
                    circleRadius.Add((int)radius);
                }
            }

            try
            {
                return(getLoctaionOfCircle(bits, circleX, circleY, circleRadius));
            }


            catch (ArgumentOutOfRangeException)
            {
                circleX.Add(0);
                circleY.Add(0);
                circleRadius.Add(0);

                return(getLoctaionOfCircle(bits, circleX, circleY, circleRadius));
            }
        }
Example #4
0
        private void colorOfPlayer(Bitmap bitmap)
        {
            HSLFiltering GreenFilter = new HSLFiltering();

            GreenFilter.Hue        = new IntRange(200, 250);
            GreenFilter.Saturation = new Range(0.5f, 1);
            GreenFilter.Luminance  = new Range(0.2f, 0.6f);
            GreenFilter.ApplyInPlace(bitmap);
            wbt             = (WriteableBitmap)bitmap;
            img2.Source     = wbt;
            img2.Visibility = Visibility.Visible;
            //    this.PictureBox.Source = (ImageSource)concatenate.Apply(this.img2);

            BlobCounter blobCounter = new AForge.Imaging.BlobCounter();

            blobCounter.ObjectsOrder = ObjectsOrder.Area;
            blobCounter.FilterBlobs  = true;
            blobCounter.MinHeight    = 10;
            blobCounter.MinWidth     = 10;
            blobCounter.ProcessImage(bitmap);
            Blob[]             blobs        = blobCounter.GetObjectsInformation();
            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();


            try {
                for (int i = 0, n = blobs.Length; i < n; i++)
                {
                    List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);
                    AForge.Point    center;
                    float           radius;
                    // is circle ?
                    if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                    {
                        if ((blobs[i].Area < 17000) && (blobs[i].Area > 3000))
                        {
                            score = score + 2;
                        }
                        else if ((blobs[i].Area < 3000) && (blobs[i].Area > 1300))
                        {
                            score = score + 4;
                        }
                        else if (blobs[i].Area < 1300)
                        {
                            score = score + 6;
                        }
                    }
                }
            }catch (Exception eeeee)
            {
            }

            text_score.Text = "" + score;
        }
        public static bool HaveLabelRF(Bitmap imagePassport)
        {
            bool haveLabel = false;

            // 1- grayscale image
            Bitmap grayImage = AForge.Imaging.Filters.Grayscale.CommonAlgorithms.BT709.Apply(imagePassport);

            // 2 - Otsu thresholding
            AForge.Imaging.Filters.OtsuThreshold threshold = new AForge.Imaging.Filters.OtsuThreshold();
            Bitmap binaryImage = threshold.Apply(grayImage);

            AForge.Imaging.Filters.Invert invertFilter = new AForge.Imaging.Filters.Invert();
            Bitmap invertImage = invertFilter.Apply(binaryImage);

            // 3 - Blob counting
            BlobCounter blobCounter = new BlobCounter();

            blobCounter.FilterBlobs = true;
            blobCounter.MinWidth    = 10;
            blobCounter.MinWidth    = 10;
            blobCounter.ProcessImage(invertImage);
            Blob[] blobs = blobCounter.GetObjectsInformation();

            // 4 - check shape of each blob
            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();
            int count = 0;

            foreach (Blob blob in blobs)
            {
                List <AForge.IntPoint> edgePoint = blobCounter.GetBlobsEdgePoints(blob);

                // check if shape looks like a circle
                AForge.Point center;
                float        radius;

                if (shapeChecker.IsCircle(edgePoint, out center, out radius))
                {
                    count++;
                    Rectangle cloneRect = new Rectangle((int)(center.X - radius), (int)(center.Y - radius + 1.0), (int)(radius * 2) + 1, (int)(radius * 2) + 1);
                    Bitmap    RF        = new Bitmap(binaryImage.Clone(cloneRect, binaryImage.PixelFormat), 32, 32);
                    Bitmap    RF2       = AForge.Imaging.Filters.Grayscale.CommonAlgorithms.BT709.Apply(RF);
                    Bitmap    RF3       = threshold.Apply(RF2);

                    if (CompareLabel(RF3) > 70.0)
                    {
                        haveLabel = true;
                    }
                }
            }
            return(haveLabel);
        }
        private void checkShape(SimpleShapeChecker shapeChecker, List <IntPoint> edgePts)
        {
            AForge.Point    center;
            float           radius;
            List <IntPoint> corners;

            if (edgePts.Count > 4 && shapeChecker.IsCircle(edgePts, out center, out radius))
            {
                //shape is a circle
                drawEllipse(center, radius);
                shapeCount[0]++;
            }
            else if (edgePts.Count > 3 && shapeChecker.IsConvexPolygon(edgePts, out corners))
            {
                PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners);

                if (subType == PolygonSubType.Unknown)
                {
                    shapeCount[4]++;
                }
                else if (subType == PolygonSubType.Square)
                {
                    shapeCount[2]++;
                }
                else if (subType == PolygonSubType.Rectangle)
                {
                    shapeCount[3]++;
                }
                else if (subType == PolygonSubType.Trapezoid)
                {
                    shapeCount[5]++;
                }
                else if (subType == PolygonSubType.EquilateralTriangle)
                {
                    shapeCount[1]++;
                }
                else if (subType == PolygonSubType.IsoscelesTriangle)
                {
                    shapeCount[1]++;
                }

                drawPolygon(corners);
            }
            else if (shapeChecker.IsTriangle(edgePts))
            {
                //triangle
                shapeCount[1]++;
            }
        }
Example #7
0
        public Bitmap DetectCircle(Bitmap image)
        {
            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();
            // locate objects using blob counter
            BlobCounter blobCounter = new BlobCounter();

            blobCounter.ProcessImage(image);
            Blob[] blobs = blobCounter.GetObjectsInformation();
            // create Graphics object to draw on the image and a pen
            Graphics g      = Graphics.FromImage(image);
            Pen      redPen = new Pen(Color.Red, 2);

            // check each object and draw circle around objects, which
            // are recognized as circles
            for (int i = 0, n = blobs.Length; i < n; i++)
            {
                List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);
                try
                {
                    shapeChecker.CheckShapeType(edgePoints);
                }
                catch (Exception)
                {
                    continue;
                }

                List <IntPoint> corners;
                AForge.Point    center;
                float           radius;
                if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                {
                    g.DrawEllipse(redPen,
                                  (int)(center.X - radius),
                                  (int)(center.Y - radius),
                                  (int)(radius * 2),
                                  (int)(radius * 2));
                }
                else if (shapeChecker.IsQuadrilateral(edgePoints, out corners))
                {
                    g.DrawPolygon(redPen, ToPointsArray(corners));
                }
            }
            redPen.Dispose();
            g.Dispose();
            return(image);
        }
Example #8
0
        /// <summary>
        /// APPLY FILTER TO IMAGE
        /// </summary>
        /// <param name="bgSelect">TRUE, SET BACKGROUND FILTER. FALSE, SET COLONY FILTER</param>
        /// <returns></returns>
        private List <ColonyModel> ProcessIMG(bool bgSelect)
        {
            if (bgSelect)
            {
                // SET FILTER WITH BG COLOR
                FilterImgBgSelect();
            }
            else
            {
                // SET FILTER WITH COLONY COLOR
                FilterImgColonySelect();
            }

            // INIT BLOB COUNTER
            SetBlobCounter();

            blobCounter.ProcessImage(bitmapData);
            BlobCounterToList(blobCounter.GetObjectsInformation());
            bitmap.UnlockBits(bitmapData);

            // SET DISTORTION
            shapeChecker.MinAcceptableDistortion = 0.2f;
            shapeChecker.RelativeDistortionLimit = 0.2f;

            var cellLijst = new List <ColonyModel>();

            // DRAW CIRCLE AROUND BLOB
            for (int i = 0, n = blobList.Count; i < n; i++)
            {
                List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobList[i]);

                AForge.Point center;
                float        radius;

                // IF SHAPE IS CIRCLE
                if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                {
                    // ADD COLONY TO LIST
                    cellLijst.Add(new ColonyModel(center, radius));
                }
            }
            this.blobList.Clear();
            return(cellLijst);
        }
Example #9
0
        public void blob_detect()
        {
            Bitmap      image = this.scanned_image;
            BlobCounter blob  = new BlobCounter();

            blob.FilterBlobs = false;

            int blob_ht_width = 30;

            blob.MinHeight = blob_ht_width;
            blob.MinWidth  = blob_ht_width;
            blob.ProcessImage(image);

            Blob[]             b            = blob.GetObjectsInformation();
            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

            /*blob_counter.Text = b.Length.ToString();
             * Graphics g = Graphics.FromImage(image2);
             * Pen yellowPen = new Pen(Color.Yellow, 5);
             * Pen redPen = new Pen(Color.Red, 5);
             * Pen greenPen = new Pen(Color.Green, 5);
             * int b_counter = 0;
             */
            for (int i = 0, n = b.Length; i < n; i++)
            {
                List <IntPoint> edgePoints = blob.GetBlobsEdgePoints(b[i]);
                List <IntPoint> edges      = new List <IntPoint>();
                AForge.Point    center;
                float           radius;

                if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                {
                    if (b[i].Fullness * 100 >= 40 && b[i].Fullness * 100 < 100 && radius > 10)
                    {
                        Coordinate coor = new Coordinate(center.X, center.Y);
                        BLOB       blb  = new BLOB(coor, radius);
                        useful.Add(blb);
                    }
                }
            }
        }
Example #10
0
        /// <summary>
        /// Finds circles - zoom is NOT compensated for in returned results
        /// </summary>
        /// <returns>Graphic coordinates with zoom not accounted for for found circles</returns>
        public static List <Shapes.Circle> FindCircles(VideoProcessing vp, Bitmap frame)
        {
            // locating objects
            if (frame == null)
            {
                return(null);
            }
            BlobCounter blobCounter = new BlobCounter();

            blobCounter.FilterBlobs = true;
            blobCounter.MinHeight   = 5;
            blobCounter.MinWidth    = 5;
            blobCounter.ProcessImage(frame);
            Blob[] blobs = blobCounter.GetObjectsInformation();

            List <Shapes.Circle> Circles = new List <Shapes.Circle>();

            for (int i = 0, n = blobs.Length; i < n; i++)
            {
                SimpleShapeChecker shapeChecker = new SimpleShapeChecker();
                List <IntPoint>    edgePoints   = blobCounter.GetBlobsEdgePoints(blobs[i]);
                Point center;
                float radius;

                // is circle ?
                if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                {
                    if (radius > 3)    // filter out some noise
                    {
                        var circle = new Shapes.Circle(center.X, center.Y, radius);
                        Circles.Add(circle);
                    }
                }
            }
            SetVideoProcessing(Circles, vp);
            return(Circles);
        }
Example #11
0
        /// <summary>
        /// Detect Blobs in the bitmap image
        /// </summary>
        /// <param name="inputImage">Input bitmap image (Gray or RGB)</param>
        /// <param name="minFullness"> 0 if you don't want a fullness filter</param>
        /// <param name="maxNumOfFilteredBlobs"> How many filtered blob do you want be save in blobs_filter list</param>
        ///
        /// <returns></returns>
        public Blob_Aforge(Bitmap inputImage, int minWidth, int maxWidth, int minHeight, int maxHeight, double minFullness, int maxNumOfFilteredBlobs)
        {
            try
            {
                leftEdges.Clear();
                rightEdges.Clear();
                topEdges.Clear();
                bottomEdges.Clear();
                hulls.Clear();
                //quadrilaterals.Clear();

                ///Get Image
                this.image = AForge.Imaging.Image.Clone(inputImage, PixelFormat.Format24bppRgb);//

                _imageWidth  = this.image.Width;
                _imageHeight = this.image.Height;



                ///Size Filter
                blobCounter.FilterBlobs  = true;
                blobCounter.MinHeight    = minHeight;
                blobCounter.MinWidth     = minWidth;
                blobCounter.MaxHeight    = maxHeight;
                blobCounter.MaxWidth     = maxWidth;
                blobCounter.ObjectsOrder = ObjectsOrder.Area;


                ///Detection
                ///
                blobCounter.ProcessImage(this.image);
                blobs_all = blobCounter.GetObjectsInformation();


                GrahamConvexHull grahamScan = new GrahamConvexHull();

                foreach (Blob blob in blobs_all)
                {
                    fullness = blob.Fullness;



                    if (fullness > minFullness & blobs_Filtered.Count < maxNumOfFilteredBlobs)///Fullness Filter
                    {
                        List <IntPoint> leftEdge  = new List <IntPoint>();
                        List <IntPoint> rightEdge = new List <IntPoint>();
                        //  List<IntPoint> topEdge = new List<IntPoint>();
                        //  List<IntPoint> bottomEdge = new List<IntPoint>();

                        // collect edge points
                        blobCounter.GetBlobsLeftAndRightEdges(blob, out leftEdge, out rightEdge);
                        //  blobCounter.GetBlobsTopAndBottomEdges(blob, out topEdge, out bottomEdge);

                        leftEdges.Add(blob.ID, leftEdge);
                        rightEdges.Add(blob.ID, rightEdge);
                        //   topEdges.Add(blob.ID, topEdge);
                        //  bottomEdges.Add(blob.ID, bottomEdge);

                        // find convex hull
                        List <IntPoint> edgePoints = new List <IntPoint>();
                        edgePoints.AddRange(leftEdge);
                        edgePoints.AddRange(rightEdge);

                        shapeChecker.MinAcceptableDistortion = (float)0.5;
                        shapeChecker.RelativeDistortionLimit = (float)0.15;

                        if (shapeChecker.IsCircle(edgePoints))
                        {
                            blobs_Filtered.Add(blob);
                            List <IntPoint> hull = grahamScan.FindHull(edgePoints);
                            hulls.Add(blobs_Filtered.Count - 1, hull);//sinchronized with blobs_filtered items
                        }
                    }
                }



                DrawBlobImage();
            }
            catch (Exception error)
            {
                //System.Windows.Forms.MessageBox.Show(error.ToString());
                // METState.Current.ErrorSound.Play();
            }
        }
        private void ProcessImage(Bitmap bitmap)
        {
            // lock image
            BitmapData bitmapData = bitmap.LockBits(
                new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                ImageLockMode.ReadWrite, bitmap.PixelFormat);

            // step 1 - turn background to black
            ColorFiltering colorFilter = new ColorFiltering();

            colorFilter.Red              = new IntRange(Properties.Settings.Default.camFilterRed1, Properties.Settings.Default.camFilterRed2);
            colorFilter.Green            = new IntRange(Properties.Settings.Default.camFilterGreen1, Properties.Settings.Default.camFilterGreen2);
            colorFilter.Blue             = new IntRange(Properties.Settings.Default.camFilterBlue1, Properties.Settings.Default.camFilterBlue2);
            colorFilter.FillOutsideRange = Properties.Settings.Default.camFilterOutside;

            colorFilter.ApplyInPlace(bitmapData);

            // step 2 - locating objects
            BlobCounter blobCounter = new BlobCounter();

            blobCounter.FilterBlobs = true;
            blobCounter.MinHeight   = (int)Properties.Settings.Default.camShapeSizeMin * (int)cameraZoom;
            blobCounter.MinWidth    = (int)Properties.Settings.Default.camShapeSizeMin * (int)cameraZoom;
            blobCounter.MaxHeight   = (int)Properties.Settings.Default.camShapeSizeMax * (int)cameraZoom;
            blobCounter.MaxWidth    = (int)Properties.Settings.Default.camShapeSizeMax * (int)cameraZoom;

            blobCounter.ProcessImage(bitmapData);

            Blob[] blobs = blobCounter.GetObjectsInformation();
            bitmap.UnlockBits(bitmapData);

            // step 3 - check objects' type and highlight
            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

            shapeChecker.MinAcceptableDistortion = (float)Properties.Settings.Default.camShapeDist;
            shapeChecker.RelativeDistortionLimit = (float)Properties.Settings.Default.camShapeDistMax;

            Graphics g         = Graphics.FromImage(bitmap);
            Pen      yellowPen = new Pen(Color.Yellow, 5); // circles
            Pen      redPen    = new Pen(Color.Red, 10);   // circles
            Pen      greenPen  = new Pen(Color.Green, 5);  // known triangle

            double lowestDistance = xmid;
            double distance;

            shapeFound = false;
            AForge.Point center;
            double       shapeRadius = 1;

            for (int i = 0, n = blobs.Length; i < n; i++)
            {
                List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);
                System.Single   radius;
                // is circle ?
                //          g.DrawPolygon(greenPen, ToPointsArray(edgePoints));

                if (Properties.Settings.Default.camShapeCircle && shapeChecker.IsCircle(edgePoints, out center, out radius))
                {
                    shapeFound = true;
                    distance   = center.DistanceTo((AForge.Point)picCenter);
                    g.DrawEllipse(yellowPen,
                                  (float)(shapeCenter.X - shapeRadius), (float)(shapeCenter.Y - shapeRadius),
                                  (float)(shapeRadius * 2), (float)(shapeRadius * 2));

                    if (lowestDistance > Math.Abs(distance))
                    {
                        lowestDistance = Math.Abs(distance);
                        shapeCenter    = center;
                        shapeRadius    = radius;
                    }
                }
                List <IntPoint> corners;
                if (Properties.Settings.Default.camShapeRect && shapeChecker.IsQuadrilateral(edgePoints, out corners))  //.IsConvexPolygon
                {
                    IntPoint minxy, maxxy, centxy;
                    shapeFound = true;
                    PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners);
                    g.DrawPolygon(yellowPen, ToPointsArray(corners));
                    PointsCloud.GetBoundingRectangle(corners, out minxy, out maxxy);
                    centxy   = (minxy + maxxy) / 2;
                    distance = picCenter.DistanceTo(centxy);// PointsCloud.GetCenterOfGravity(corners));
                    if (lowestDistance > Math.Abs(distance))
                    {
                        lowestDistance = Math.Abs(distance);
                        shapeCenter    = centxy;                      // PointsCloud.GetCenterOfGravity(corners);
                        shapeRadius    = maxxy.DistanceTo(minxy) / 2; // 50;
                    }
                }
            }
            if (shapeFound)
            {
                g.DrawEllipse(redPen,
                              (float)(shapeCenter.X - shapeRadius * 1.2), (float)(shapeCenter.Y - shapeRadius * 1.2),
                              (float)(shapeRadius * 2.4), (float)(shapeRadius * 2.4));
            }

            yellowPen.Dispose();
            redPen.Dispose();
            greenPen.Dispose();
            g.Dispose();
            pictureBoxVideo.BackgroundImage = bitmap;
        }
Example #13
0
        void reader_IRFrameArrived(object sender, MultiSourceFrameArrivedEventArgs e)
        {
            if (mode == 1)
            {
                return;
            }

            var reference = e.FrameReference.AcquireFrame();

            using (InfraredFrame frame = reference.InfraredFrameReference.AcquireFrame())
            {
                if (frame != null)
                {
                    warten.Visible = false;

                    int      width     = frame.FrameDescription.Width;
                    int      height    = frame.FrameDescription.Height;
                    ushort[] data      = new ushort[width * height];
                    byte[]   pixelData = new byte[width * height * 4];
                    possibleTracker = new string[width * height * 4];
                    int xcoord = 0;
                    int ycoord = 0;

                    frame.CopyFrameDataToArray(data);
                    int    akt    = 0;
                    Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb);
                    for (int infraredIndex = 0; infraredIndex < data.Length; infraredIndex++)
                    {
                        ushort ir        = data[infraredIndex];
                        byte   intensity = (byte)(ir >> 8);

                        pixelData[infraredIndex * 4]     = intensity; // Blue
                        pixelData[infraredIndex * 4 + 1] = intensity; // Green
                        pixelData[infraredIndex * 4 + 2] = intensity; // Red
                        pixelData[infraredIndex * 4 + 3] = 255;       //Brightness
                    }
                    var bitmapdata = bitmap.LockBits(
                        new Rectangle(0, 0, width, height),
                        ImageLockMode.WriteOnly,
                        bitmap.PixelFormat
                        );
                    IntPtr ptr = bitmapdata.Scan0;

                    Marshal.Copy(pixelData, 0, ptr, pixelData.Length);
                    bitmap.UnlockBits(bitmapdata);
                    bitmap.RotateFlip(RotateFlipType.Rotate180FlipY);

                    counter = new BlobCounter();
                    EuclideanColorFiltering filter = new EuclideanColorFiltering();
                    //ResizeNearestNeighbor filter2 = new ResizeNearestNeighbor(1920, 1080);
                    filter.CenterColor = new RGB(Color.White);   //Pure White
                    filter.Radius      = (short)trackBar1.Value; //Increase this to allow off-whites
                    filter.FillOutside = false;
                    filter.FillColor   = new RGB(Color.White);   //Replacement Color

                    Bitmap bmp = filter.Apply(bitmap);

                    //filter2.Apply(bmp);
                    //filter3.Apply(bmp);

                    //filter.CenterColor = new RGB(0, 0, 0);
                    //filter.Radius = 100;
                    //filter.ApplyInPlace(bmp);
                    counter.MinWidth  = 100;
                    counter.MinHeight = 100;
                    //counter.FilterBlobs = true;
                    counter.BackgroundThreshold = Color.Gray;
                    counter.ProcessImage(bmp);
                    Blob[]             blobs        = counter.GetObjectsInformation();
                    Pen                redPen       = new Pen(Color.Red, 20);//Kreisradius
                    Graphics           g            = Graphics.FromImage(bmp);
                    SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

                    for (int i = 0; i < blobs.Length; i++)
                    {
                        List <IntPoint> edgePoints = counter.GetBlobsEdgePoints(blobs[i]);

                        AForge.Point center;
                        float        radius;

                        if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                        {
                            g.DrawEllipse(redPen,
                                          (int)(center.X - radius),
                                          (int)(center.Y - radius),
                                          (int)(radius * 2),
                                          (int)(radius * 2));
                            if (kreise == 1)
                            {
                                ecken1_x = (int)center.X;
                                ecken1_y = (int)center.Y;
                            }
                            if (kreise == 2)
                            {
                                ecken2_x = (int)center.X;
                                ecken2_y = (int)center.Y;
                            }
                            if (kreise == 3)
                            {
                                ecken3_x = (int)center.X;
                                ecken3_y = (int)center.Y;
                            }
                            if (kreise == 4)
                            {
                                ecken4_x = (int)center.X;
                                ecken4_y = (int)center.Y;
                                kreise   = 0;
                            }
                            kreise++;
                        }

                        //anzeige.Text = center.X.ToString() + " " + center.Y.ToString();
                        //anzeige.Text = ecken_x[z].ToString() + " " + ecken_x[z].ToString();
                        anzeige.Text = "Punkt 1: " + ecken1_x + " " + ecken1_y + "\n" + "Punkt 2: " + ecken2_x + " " + ecken2_y + "\n" + "Punkt 3: " + ecken3_x + " " + ecken3_y + "\n" + "Punkt 4: " + ecken4_x + " " + ecken4_y;
                    }
                    pictureBox1.Image = bmp;
                }
                else
                {
                    warten.Visible = true;
                }
            }
        }
Example #14
0
        private void button1_Click_1(object sender, EventArgs e)
        {
            BitmapFilter.NegativeThreshold(ref loaded, ref processed, 174);
            pictureBox1.Image = processed;
            double sum = 0;
            //locate objects
            BlobCounter blobCounter = new BlobCounter();

            blobCounter.ProcessImage(processed);
            Blob[] blobs = blobCounter.GetObjectsInformation();

            Graphics g      = Graphics.FromImage(processed);
            Pen      redPen = new Pen(Color.Red, 2);

            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

            for (int i = 0, n = blobs.Length; i < n; i++)
            {
                List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);

                AForge.Point center;
                float        radius;

                if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                {
                    g.DrawEllipse(redPen,
                                  (int)(center.X - radius),
                                  (int)(center.Y - radius),
                                  (int)(radius * 2),
                                  (int)(radius * 2));

                    if (blobs[i].Area >= 240 && blobs[i].Area <= 290)
                    {
                        sum += 0.05;
                    }
                    if (blobs[i].Area >= 315 && blobs[i].Area <= 360)
                    {
                        sum += 0.1;
                    }
                    if (blobs[i].Area >= 420 && blobs[i].Area <= 500)
                    {
                        sum += 0.25;
                    }
                    if (blobs[i].Area >= 610 && blobs[i].Area <= 680)
                    {
                        sum += 1;
                    }
                    if (blobs[i].Area >= 760 && blobs[i].Area <= 840)
                    {
                        sum += 5;
                    }
                }
            }


            redPen.Dispose();
            g.Dispose();


            MessageBox.Show("Total: " + sum + "\nCount of coins: " + blobs.Length);
            pictureBox1.Image = loaded;
        }
        public List <string> Procesar_Circulos(Bitmap BMP)
        {
            //Módulo para encontrar los círculos en una imagen
            List <string> Datos      = new List <string>();                                                //crear lista datos k almacenas los datos recopilados
            Rectangle     RECTANGULO = new Rectangle(0, 0, BMP.Width, BMP.Height);                         //declaramos una variable tipo rectangulo k almacenar ala circunferenia
            BitmapData    BMPDATOS   = BMP.LockBits(RECTANGULO, ImageLockMode.ReadWrite, BMP.PixelFormat); //Bitmapdata obtiene los datos de la imagen

            Bitmap A = new Bitmap(BMP.Width, BMP.Height);                                                  //bitmap vacio k almacena el borde de la imagen procesada

            ColorFiltering FILTRO = new ColorFiltering();                                                  //filtro k se ablicara a la imagen

            FILTRO.Red   = new IntRange(0, 100);                                                           //recibe tonalidades de 0 a 100 en sus 3 capas
            FILTRO.Green = new IntRange(0, 100);
            FILTRO.Blue  = new IntRange(0, 100);

            FILTRO.FillOutsideRange = false;
            FILTRO.ApplyInPlace(BMPDATOS);

            //BUSCA LOS ELEMENTOS
            BlobCounter ELEMENTOS = new BlobCounter(); //alamacena  los elementos encontrados en la imagen

            ELEMENTOS.FilterBlobs = true;
            ELEMENTOS.MinHeight   = 20; //ALTURA y alcho MINIMA del objeto
            ELEMENTOS.MinWidth    = 20;

            ELEMENTOS.ProcessImage(BMPDATOS);//obtiene los elementos de la imagen
            Blob[] ELEMENTOSINFO = ELEMENTOS.GetObjectsInformation();
            BMP.UnlockBits(BMPDATOS);

            SimpleShapeChecker BUSCADOR = new SimpleShapeChecker(); //PARA DETERMINAR LA FORMA DE LOS ELEMENTOS ENCONTRADOS
            Graphics           DIBUJO   = Graphics.FromImage(BMP);  //PARA DIBUJAR LOS ELEMENTOS
            Graphics           DIBUJO2  = Graphics.FromImage(A);

            Pen CIRCULOS      = new Pen(Color.Black, 5); //CIRCULOS
            Pen TRIANGULOS    = new Pen(Color.Black, 5); //TRIANGULOS
            Pen CUADRILATEROS = new Pen(Color.Black, 5); //CUADRILATEROS
            Pen TRAZO         = new Pen(Color.Red);      //'PARA SEÑALIZAR LAS FORMAS


            for (int i = 0; i < ELEMENTOSINFO.Length; i++)                                                                                                                       //recorremos la imagen pixel a pixel
            {
                System.Collections.Generic.List <AForge.IntPoint> PUNTOS = ELEMENTOS.GetBlobsEdgePoints(ELEMENTOSINFO[i]);                                                       //'OBTIENE LOS PUNTOS DE LA FORMA
                AForge.Point CENTRO = new AForge.Point();                                                                                                                        //'CENTRO DEL CIRCULO
                float        RADIO  = new float();                                                                                                                               //'RADIO DEL CIRCULO

                if (BUSCADOR.IsCircle(PUNTOS, out CENTRO, out RADIO))                                                                                                            //
                {                                                                                                                                                                //'SI ES UN CIRCULO dibujamos
                    DIBUJO.DrawEllipse(CIRCULOS, (int)Math.Round(CENTRO.X - RADIO), (int)Math.Round(CENTRO.Y - RADIO), (int)Math.Round(RADIO * 2), (int)Math.Round(RADIO * 2));  // 'DIBUJA EL CIRCULO
                    DIBUJO2.DrawEllipse(CIRCULOS, (int)Math.Round(CENTRO.X - RADIO), (int)Math.Round(CENTRO.Y - RADIO), (int)Math.Round(RADIO * 2), (int)Math.Round(RADIO * 2)); // 'DIBUJA EL CIRCULO

                    Datos.Add(CENTRO.X + "-" + CENTRO.Y + "-" + RADIO);
                }
            }


            //Mostrar_Imagen A
            Pasar_Imagen pa = new Pasar_Imagen(Mostrar_Imagen);

            this.Invoke(pa, A);

            return(Datos);
        }
Example #16
0
        private void kamerica_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            Bitmap     slika      = (Bitmap)eventArgs.Frame.Clone();
            BitmapData bitmapData = slika.LockBits(
                new Rectangle(0, 0, slika.Width, slika.Height),
                ImageLockMode.ReadWrite, slika.PixelFormat);

            // step 1 - turn background to black
            ColorFiltering colorFilter = new ColorFiltering();

            colorFilter.Red              = new IntRange(0, 64);
            colorFilter.Green            = new IntRange(0, 64);
            colorFilter.Blue             = new IntRange(0, 64);
            colorFilter.FillOutsideRange = false;

            colorFilter.ApplyInPlace(bitmapData);

            // step 2 - locating objects
            BlobCounter blobCounter = new BlobCounter();

            blobCounter.FilterBlobs = true;
            blobCounter.MinHeight   = 5;
            blobCounter.MinWidth    = 5;

            blobCounter.ProcessImage(bitmapData);
            Blob[] blobs = blobCounter.GetObjectsInformation();
            slika.UnlockBits(bitmapData);

            // step 3 - check objects' type and highlight
            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

            Graphics g         = Graphics.FromImage(slika);
            Pen      yellowPen = new Pen(Color.Yellow, 2); // circles
            Pen      redPen    = new Pen(Color.Red, 2);    // quadrilateral
            Pen      brownPen  = new Pen(Color.Brown, 2);  // quadrilateral with known sub-type
            Pen      greenPen  = new Pen(Color.Green, 2);  // known triangle
            Pen      bluePen   = new Pen(Color.Blue, 2);   // triangle

            for (int i = 0, n = blobs.Length; i < n; i++)
            {
                List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);

                // calculate center point
                AForge.Point center;
                // calculate radius
                float radius;

                // is circle ?
                if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                {
                    g.DrawEllipse(yellowPen,
                                  (float)(center.X - radius), (float)(center.Y - radius),
                                  (float)(radius * 2), (float)(radius * 2));
                }
                else
                {
                    List <IntPoint> corners;

                    // is triangle or quadrilateral
                    if (shapeChecker.IsConvexPolygon(edgePoints, out corners))
                    {
                        // get sub-type
                        PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners);

                        Pen pen;

                        if (subType == PolygonSubType.Unknown)
                        {
                            pen = (corners.Count == 4) ? redPen : bluePen;
                        }
                        else
                        {
                            pen = (corners.Count == 4) ? brownPen : greenPen;
                        }

                        g.DrawPolygon(pen, ToPointsArray(corners));
                    }
                }
            }

            yellowPen.Dispose();
            redPen.Dispose();
            greenPen.Dispose();
            bluePen.Dispose();
            brownPen.Dispose();
            g.Dispose();



            pictureBox1.Image = slika;
        }
Example #17
0
        //private List<Triangle> LoadImage()
        //{
        //    // load arrow bitmap
        //    string embeddedFileName = CheckForUploadedFile();
        //    Assembly assembly = this.GetType().Assembly;
        //    Bitmap image = new Bitmap(assembly.GetManifestResourceStream(embeddedFileName));
        //    List<Triangle>  triangleList;
        //   // triangleList=  ProcessImage(image);
        //    return triangleList;
        //}

        private List <Triangle> ProcessImage()
        {
            List <Triangle> TriangleList = new List <Triangle>();

            List <ULBounds> triBounds = new List <ULBounds>();

            int currentMaxX = 0;
            int currentMaxY = 0;

            int currentUBoundsX = 0;
            int currentUBoundsY = 0;

            int    currentCol = 0;
            String currentRow = String.Empty;

            string embeddedFileName = CheckForUploadedFile();

            if (embeddedFileName == String.Empty)
            {
                TriangleList = NoTriangleFound();
                return(TriangleList);
            }

            Bitmap bitmap = (Bitmap)Bitmap.FromFile(embeddedFileName);
            // Triangle Class List



            // values needed to find area of a triangle
            // double[] X;
            //  double[] Y;
            int    z;
            double area;

            // lock image

            String filePath = CheckForUploadedFile();

            Int16 Tol      = 38;
            Color replace1 = new Color();

            replace1 = Color.FromArgb(129, 187, 237);

            Color newColor = new Color();

            newColor = Color.FromArgb(0, 0, 0);

            ImageConverter ic = new ImageConverter();


            Color replace2 = new Color();

            replace2 = Color.FromArgb(199, 221, 234);
            Tol      = 38;

            System.Drawing.Image tmpImage = System.Drawing.Image.FromFile(filePath);
            tmpImage = ColorReplace(tmpImage, Tol, replace1, newColor);

            ColorReplace(tmpImage, Tol, replace2, newColor);

            // UpdatePictureBoxPositionOutPut();


            bitmap = new Bitmap(tmpImage);

            BitmapData bitmapData = bitmap.LockBits(
                new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                ImageLockMode.ReadWrite, bitmap.PixelFormat);



            // step 1 - turn background to black
            ColorFiltering colorFilter = new ColorFiltering();

            colorFilter.Red              = new IntRange(0, 64);
            colorFilter.Green            = new IntRange(0, 64);
            colorFilter.Blue             = new IntRange(0, 64);
            colorFilter.FillOutsideRange = false;

            colorFilter.ApplyInPlace(bitmapData);

            // step 2 - locating objects
            BlobCounter blobCounter = new BlobCounter();

            blobCounter.FilterBlobs = true;
            blobCounter.MinHeight   = 5;
            blobCounter.MinWidth    = 5;

            blobCounter.ProcessImage(bitmapData);
            Blob[] blobs = blobCounter.GetObjectsInformation();
            bitmap.UnlockBits(bitmapData);

            // step 3 - check objects' type and highlight
            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

            Graphics g         = Graphics.FromImage(bitmap);
            Pen      yellowPen = new Pen(Color.Yellow, 2); // circles
            Pen      redPen    = new Pen(Color.Red, 2);    // quadrilateral
            Pen      brownPen  = new Pen(Color.Brown, 2);  // quadrilateral with known sub-type
            Pen      greenPen  = new Pen(Color.Green, 2);  // known triangle
            Pen      bluePen   = new Pen(Color.Blue, 2);   // triangle

            int triFound = 0;

            for (int i = 0, n = blobs.Length; i < n; i++)
            {
                List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);

                DoublePoint center;
                double      radius;
                int         tempX = 0;
                int         tempY = 0;

                int    tempCol = 0;
                String tempRow = string.Empty;


                // is circle ?
                if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                {
                    g.DrawEllipse(yellowPen,
                                  (float)(center.X - radius), (float)(center.Y - radius),
                                  (float)(radius * 2), (float)(radius * 2));
                }
                else
                {
                    List <IntPoint> corners;

                    // is triangle or quadrilateral
                    if (shapeChecker.IsConvexPolygon(edgePoints, out corners))
                    {
                        // get sub-type
                        PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners);

                        Pen pen;

                        if (subType == PolygonSubType.Unknown)
                        {
                            pen = (corners.Count == 4) ? redPen : bluePen;
                        }
                        else
                        {
                            pen = (corners.Count == 4) ? brownPen : yellowPen;


                            double[] X = { corners[0].X, corners[1].X, corners[2].X };
                            double[] Y = { corners[0].Y, corners[1].Y, corners[2].Y };
                            z = X.Length;

                            area = polygonArea(X, Y, z);

                            if (area < 40000)
                            {
                                triFound = triFound + 1;


                                Triangle tmpTri = new Triangle();
                                ULBounds tmpULB = new ULBounds();
                                tmpTri.Name = "Triangle " + triFound.ToString();
                                tmpTri.PtAx = corners[0].X;
                                tmpTri.PtAy = corners[0].Y;

                                if (tmpTri.PtAx > currentMaxX)
                                {
                                    currentMaxX = tmpTri.PtAx;
                                }

                                if (tmpTri.PtAy > currentMaxY)
                                {
                                    currentMaxY = tmpTri.PtAy;
                                }


                                tmpTri.PtBx = corners[1].X;
                                tmpTri.PtBy = corners[1].Y;

                                if (tmpTri.PtBx > currentMaxX)
                                {
                                    currentMaxX = tmpTri.PtBx;
                                }

                                if (tmpTri.PtBy > currentMaxY)
                                {
                                    currentMaxY = tmpTri.PtBy;
                                }



                                tmpTri.PtCx = corners[2].X;
                                tmpTri.PtCy = corners[2].Y;

                                if (tmpTri.PtCx > currentMaxX)
                                {
                                    currentMaxX = tmpTri.PtCx;
                                }

                                if (tmpTri.PtBy > currentMaxY)
                                {
                                    currentMaxY = tmpTri.PtBy;
                                }

                                if (currentCol == 0)
                                {
                                    currentCol++; tempCol = currentCol; currentUBoundsY = currentMaxY;
                                }
                                else
                                {
                                    currentCol = GetMaxColumn(triBounds);
                                }

                                if (currentRow == string.Empty)
                                {
                                    currentRow = Increment(currentRow); tempRow = currentRow; currentUBoundsX = currentMaxX;
                                }
                                else
                                {
                                    currentRow = GetMaxRow(triBounds);
                                };


                                if (triBounds.Count == 0)
                                {
                                    //adding Row
                                    tmpULB.Col   = 0;
                                    tmpULB.Row   = tempRow;
                                    tmpULB.Lower = 0;
                                    tmpULB.Upper = currentMaxY;

                                    triBounds.Add(tmpULB);

                                    tmpULB = new ULBounds();

                                    //adding Col
                                    tmpULB.Col   = tempCol;
                                    tmpULB.Row   = String.Empty;
                                    tmpULB.Lower = 0;
                                    tmpULB.Upper = currentMaxX;

                                    triBounds.Add(tmpULB);
                                }

                                if (currentMaxX > (currentUBoundsX * 1.15))
                                {
                                    currentUBoundsX = GetMaxColumnUBounds(triBounds);
                                    if (currentMaxX > (currentUBoundsX * 1.15))
                                    {
                                        tempCol = GetMaxColumn(triBounds);

                                        tmpULB  = new ULBounds();
                                        tempCol = tempCol++;

                                        tmpULB.Col   = tempCol;
                                        tmpULB.Row   = String.Empty;
                                        tmpULB.Lower = currentUBoundsX + 1;
                                        tmpULB.Upper = currentMaxX;
                                        triBounds.Add(tmpULB);
                                    }
                                }



                                if (currentMaxY > (currentUBoundsY * 1.15))
                                {
                                    currentUBoundsY = GetMaxColumnUBounds(triBounds);
                                    if (currentMaxY > (currentUBoundsY * 1.15))
                                    {
                                        tempRow = GetMaxRow(triBounds);
                                        tmpULB  = new ULBounds();
                                        tempRow = Increment(tempRow);
                                        //adding Col
                                        tmpULB.Col   = tempCol;
                                        tmpULB.Row   = String.Empty;
                                        tmpULB.Lower = 0;
                                        tmpULB.Upper = currentMaxX;

                                        triBounds.Add(tmpULB);
                                    }
                                }


                                tmpTri.Row = currentRow.ToUpper();
                                tmpTri.Col = currentCol;


                                tmpTri.Area = polygonArea(X, Y, z);


                                TriangleList.Add(tmpTri);
                            }
                        }

                        g.DrawPolygon(pen, ToPointsArray(corners));
                    }
                }
            }

            yellowPen.Dispose();
            redPen.Dispose();
            greenPen.Dispose();
            bluePen.Dispose();
            brownPen.Dispose();
            g.Dispose();



            return(TriangleList);
        }
Example #18
0
        public void processShapes()
        {
            //Working Variables
            Pen fuschiaPen = new Pen(Color.Fuchsia, 3.0f);
            Pen aquaPen    = new Pen(Color.Aqua, 5.0f);
            Pen redPen     = new Pen(Color.Red, 3.0f);
            Pen orangePen  = new Pen(Color.Orange, 3.0f);


            //Locking Image Bits
            Bitmap workingFrame = edgeDetection();

            System.Drawing.Imaging.BitmapData bmpData = workingFrame.LockBits(new Rectangle(0, 0, workingFrame.Width, workingFrame.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, workingFrame.PixelFormat);


            //Turning the Background Black and getting rid of the green of the PCB

            /*ColorFiltering colorFilter = new ColorFiltering();
             * Threshold filter = new Threshold((int)hScrollBar1.Value);
             *
             * colorFilter.Red = new IntRange(0, hScrollBar1.Value);
             * colorFilter.Blue = new IntRange(0, hScrollBar1.Value);
             * colorFilter.Green = new IntRange(0, hScrollBar1.Value);
             */
            // colorFilter.ApplyInPlace(bmpData);
            workingFrame.UnlockBits(bmpData);



            //Identifing the Blobs in target picture
            BlobCounter blobCounter = new BlobCounter();

            blobCounter.FilterBlobs = true;
            //blobCounter.MinHeight = 5;
            //blobCounter.MinWidth = 5;
            blobCounter.MinHeight = hScrollBar2.Value;
            blobCounter.MinWidth  = hScrollBar2.Value;

            blobCounter.ProcessImage(bmpData);
            Blob[] blobs = blobCounter.GetObjectsInformation();

            //scrollableImagePanel1.Image = (Bitmap)workingFrame.Clone();
            //Classifying the objects{}
            AForge.Math.Geometry.SimpleShapeChecker shapeCheck = new SimpleShapeChecker();
            Bitmap   tempBitmap = new Bitmap(workingFrame.Width, workingFrame.Height);
            Graphics g          = Graphics.FromImage(tempBitmap);

            g.DrawImage(workingFrame, 0, 0);

            if (caseValue == 1)
            {
                scrollableImagePanel1.Image = tempBitmap;
            }
            if (caseValue == 2)
            {
                scrollableImagePanel3.Image = tempBitmap;
            }
            if (caseValue == 3)
            {
                scrollableImagePanel2.Image = tempBitmap;
            }
            if (caseValue == 4)
            {
                scrollableImagePanel5.Image = tempBitmap;
            }
            if (caseValue == 5)
            {
                scrollableImagePanel4.Image = tempBitmap;
            }
            int blobLength = blobs.Length;

            for (int i = 0; i < blobLength; i++)
            {
                List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);
                AForge.Point    center;
                float           radius;

                if (shapeCheck.IsCircle(edgePoints, out center, out radius))
                {
                    float tempLocationX = (float)(center.X - radius);
                    float tempLocationY = (float)(center.Y - radius);
                    float diameter      = radius * 2.0f;
                    g.DrawEllipse(fuschiaPen, tempLocationX, tempLocationY, diameter, diameter);
                }
                else
                {
                    List <IntPoint> corners = PointsCloud.FindQuadrilateralCorners(edgePoints);
                    if (shapeCheck.IsQuadrilateral(edgePoints, out corners))
                    {
                        Rectangle testRectangle = new Rectangle(corners[0].X, corners[0].Y, (corners[1].X - corners[0].X), corners[3].Y - corners[0].Y);
                        g.DrawRectangle(redPen, testRectangle);

                        if (shapeCheck.CheckPolygonSubType(corners) == PolygonSubType.Rectangle)
                        {
                            g.DrawPolygon(aquaPen, ToPointsArray(corners));
                        }
                        else
                        {
                            g.DrawPolygon(orangePen, ToPointsArray(corners));
                        }
                    }
                }

                //redPen.Dispose();
                //orangePen.Dispose();

                //g.Dispose();
            }
        }
Example #19
0
        private List <Star> IdentifyStars()
        {
            Blob[]             blobs      = _blobCounter.GetObjectsInformation();
            SimpleShapeChecker checker    = new SimpleShapeChecker();
            List <Star>        starlist   = new List <Star>();
            double             sumRadius  = 0;
            double             sumSquares = 0;

            foreach (Blob blob in blobs)
            {
                _token.ThrowIfCancellationRequested();

                if (blob.Rectangle.Width > _maxStarSize ||
                    blob.Rectangle.Height > _maxStarSize ||
                    blob.Rectangle.Width < _minStarSize ||
                    blob.Rectangle.Height < _minStarSize)
                {
                    continue;
                }

                // If camera cannot subSample, but crop ratio is set, use blobs that are either within or without the ROI
                if (UseROI && !InROI(blob))
                {
                    continue;
                }

                var          points = _blobCounter.GetBlobsEdgePoints(blob);
                Accord.Point centerpoint;
                float        radius;
                var          rect = new Rectangle((int)Math.Floor(blob.Rectangle.X * _inverseResizefactor), (int)Math.Floor(blob.Rectangle.Y * _inverseResizefactor), (int)Math.Ceiling(blob.Rectangle.Width * _inverseResizefactor), (int)Math.Ceiling(blob.Rectangle.Height * _inverseResizefactor));

                //Build a rectangle that encompasses the blob
                int largeRectXPos  = Math.Max(rect.X - rect.Width, 0);
                int largeRectYPos  = Math.Max(rect.Y - rect.Height, 0);
                int largeRectWidth = rect.Width * 3;
                if (largeRectXPos + largeRectWidth > imageProperties.Width)
                {
                    largeRectWidth = imageProperties.Width - largeRectXPos;
                }
                int largeRectHeight = rect.Height * 3;
                if (largeRectYPos + largeRectHeight > imageProperties.Height)
                {
                    largeRectHeight = imageProperties.Height - largeRectYPos;
                }
                var largeRect = new Rectangle(largeRectXPos, largeRectYPos, largeRectWidth, largeRectHeight);

                //Star is circle
                Star s;
                if (checker.IsCircle(points, out centerpoint, out radius))
                {
                    s = new Star {
                        Position = new Accord.Point(centerpoint.X * (float)_inverseResizefactor, centerpoint.Y * (float)_inverseResizefactor), radius = radius * _inverseResizefactor, Rectangle = rect
                    };
                }
                else     //Star is elongated
                {
                    var eccentricity = CalculateEccentricity(rect.Width, rect.Height);
                    //Discard highly elliptical shapes.
                    if (eccentricity > 0.8)
                    {
                        continue;
                    }
                    s = new Star {
                        Position = new Accord.Point(centerpoint.X * (float)_inverseResizefactor, centerpoint.Y * (float)_inverseResizefactor), radius = Math.Max(rect.Width, rect.Height) / 2, Rectangle = rect
                    };
                }

                /* get pixeldata */
                double        starPixelSum             = 0;
                int           starPixelCount           = 0;
                double        largeRectPixelSum        = 0;
                double        largeRectPixelSumSquares = 0;
                List <ushort> innerStarPixelValues     = new List <ushort>();

                for (int x = largeRect.X; x < largeRect.X + largeRect.Width; x++)
                {
                    for (int y = largeRect.Y; y < largeRect.Y + largeRect.Height; y++)
                    {
                        var pixelValue = _iarr.FlatArray[x + (imageProperties.Width * y)];
                        if (x >= s.Rectangle.X && x < s.Rectangle.X + s.Rectangle.Width && y >= s.Rectangle.Y && y < s.Rectangle.Y + s.Rectangle.Height) //We're in the small rectangle directly surrounding the star
                        {
                            if (s.InsideCircle(x, y, s.Position.X, s.Position.Y, s.radius))                                                              // We're in the inner sanctum of the star
                            {
                                starPixelSum += pixelValue;
                                starPixelCount++;
                                innerStarPixelValues.Add(pixelValue);
                            }
                            ushort    value = pixelValue;
                            PixelData pd    = new PixelData {
                                PosX = x, PosY = y, value = (ushort)value
                            };
                            s.AddPixelData(pd);
                        }
                        else     //We're in the larger surrounding holed rectangle, providing local background
                        {
                            largeRectPixelSum        += pixelValue;
                            largeRectPixelSumSquares += pixelValue * pixelValue;
                        }
                    }
                }

                s.meanBrightness = starPixelSum / (double)starPixelCount;
                double largeRectPixelCount = largeRect.Height * largeRect.Width - rect.Height * rect.Width;
                double largeRectMean       = largeRectPixelSum / largeRectPixelCount;
                s.SurroundingMean = largeRectMean;
                double largeRectStdev        = Math.Sqrt((largeRectPixelSumSquares - largeRectPixelCount * largeRectMean * largeRectMean) / largeRectPixelCount);
                int    minimumNumberOfPixels = (int)Math.Ceiling(Math.Max(_originalBitmapSource.PixelWidth, _originalBitmapSource.PixelHeight) / 1000d);

                if (s.meanBrightness >= largeRectMean + Math.Min(0.1 * largeRectMean, largeRectStdev) && innerStarPixelValues.Count(pv => pv > largeRectMean + 1.5 * largeRectStdev) > minimumNumberOfPixels)   //It's a local maximum, and has enough bright pixels, so likely to be a star. Let's add it to our star dictionary.
                {
                    sumRadius  += s.radius;
                    sumSquares += s.radius * s.radius;
                    s.CalculateHfr();
                    starlist.Add(s);
                }
            }

            // No stars could be found. Return.
            if (starlist.Count() == 0)
            {
                return(starlist);
            }

            //We are performing AF with only a limited number of stars
            if (NumberOfAFStars > 0)
            {
                //First AF exposure, let's find the brightest star positions and store them
                if (starlist.Count() != 0 && BrightestStarPositions.Count() == 0)
                {
                    if (starlist.Count() <= NumberOfAFStars)
                    {
                        BrightestStarPositions = starlist.ConvertAll(s => s.Position);
                        return(starlist);
                    }
                    else
                    {
                        starlist = starlist.OrderByDescending(s => s.radius * 0.3 + s.meanBrightness * 0.7).Take(NumberOfAFStars).ToList <Star>();
                        BrightestStarPositions = starlist.ConvertAll(i => i.Position);
                        return(starlist);
                    }
                }
                else     //find the closest stars to the brightest stars previously identified
                {
                    List <Star> topStars = new List <Star>();
                    BrightestStarPositions.ForEach(p => topStars.Add(starlist.Aggregate((min, next) => min.Position.DistanceTo(p) < next.Position.DistanceTo(p) ? min : next)));
                    return(topStars);
                }
            }

            //Now that we have a properly filtered star list, let's compute stats and further filter out from the mean
            if (starlist.Count > 0)
            {
                double avg   = sumRadius / (double)starlist.Count();
                double stdev = Math.Sqrt((sumSquares - starlist.Count() * avg * avg) / starlist.Count());
                if (_sensitivity == StarSensitivityEnum.Normal)
                {
                    starlist = starlist.Where(s => s.radius <= avg + 1.5 * stdev && s.radius >= avg - 1.5 * stdev).ToList <Star>();
                }
                else
                {
                    //More sensitivity means getting fainter and smaller stars, and maybe some noise, skewing the distribution towards low radius. Let's be more permissive towards the large star end.
                    starlist = starlist.Where(s => s.radius <= avg + 2 * stdev && s.radius >= avg - 1.5 * stdev).ToList <Star>();
                }
            }
            return(starlist);
        }
        private void ProcessImage(Bitmap bitmap)
        {
            if (CBApplyCanny.Checked)
            {
                Bitmap            video2 = (Bitmap)bitmap.Clone();
                Grayscale         gray   = new Grayscale(0.2125, 0.7154, 0.0721);
                Bitmap            video3 = gray.Apply(video2);
                CannyEdgeDetector canny  = new CannyEdgeDetector(0, 70);
                canny.ApplyInPlace(video3);
                //PictureViewerEditor.Image = (Bitmap)Image.FromFile(imageFileName);
                PBCanny.Image = (Bitmap)video3.Clone();//assign the pointer back to the clone
                //if (CBFindCircles.Checked)
                //{
                //    //System.Drawing.Image returnImage = null;
                //    //returnImage = (System.Drawing.Image)CaptureBox.Image.Clone();
                //    // Clipboard.SetImage(replacementImage);
                //    Bitmap cannyImage = (Bitmap)PBCapture.Image.Clone();
                //    ProcessImage(cannyImage);
                //    return;
                //}
                GC.Collect();
                //return;
            }
            // lock image
            BitmapData bitmapData = bitmap.LockBits(
                new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                ImageLockMode.ReadWrite, bitmap.PixelFormat);

            // step 1 - turn background to black
            ColorFiltering colorFilter = new ColorFiltering();

            colorFilter.Red              = new IntRange(0, 64);
            colorFilter.Green            = new IntRange(0, 64);
            colorFilter.Blue             = new IntRange(0, 64);
            colorFilter.FillOutsideRange = false;

            colorFilter.ApplyInPlace(bitmapData);

            // step 2 - locating objects
            BlobCounter blobCounter = new BlobCounter();

            blobCounter.FilterBlobs = true;
            blobCounter.MinHeight   = 5;
            blobCounter.MinWidth    = 5;

            blobCounter.ProcessImage(bitmapData);
            Blob[] blobs = blobCounter.GetObjectsInformation();
            bitmap.UnlockBits(bitmapData);
            PBCanny.Image = (Bitmap)bitmap.Clone();
            // step 3 - check objects' type and highlight
            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

            Graphics g         = Graphics.FromImage(bitmap);
            Pen      yellowPen = new Pen(Color.Yellow, 2); // circles
            Pen      redPen    = new Pen(Color.Red, 2);    // quadrilateral
            Pen      brownPen  = new Pen(Color.Brown, 2);  // quadrilateral with known sub-type
            Pen      greenPen  = new Pen(Color.Green, 2);  // known triangle
            Pen      bluePen   = new Pen(Color.Blue, 2);   // triangle

            for (int i = 0, n = blobs.Length; i < n; i++)
            {
                List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);

                AForge.Point center;
                float        radius;

                // is circle ?
                if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                {
                    g.DrawEllipse(yellowPen,
                                  (float)(center.X - radius), (float)(center.Y - radius),
                                  (float)(radius * 2), (float)(radius * 2));
                }
                else
                {
                    List <IntPoint> corners;

                    // is triangle or quadrilateral
                    if (shapeChecker.IsConvexPolygon(edgePoints, out corners))
                    {
                        // get sub-type
                        PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners);

                        Pen pen;

                        if (subType == PolygonSubType.Unknown)
                        {
                            pen = (corners.Count == 4) ? redPen : bluePen;
                        }
                        else
                        {
                            pen = (corners.Count == 4) ? brownPen : greenPen;
                        }

                        g.DrawPolygon(pen, ToPointsArray(corners));
                    }
                }
            }

            yellowPen.Dispose();
            redPen.Dispose();
            greenPen.Dispose();
            bluePen.Dispose();
            brownPen.Dispose();
            g.Dispose();

            // put new image to clipboard
            //Clipboard.SetDataObject(bitmap);
            // and to picture box
            PBAnalysis.Image = bitmap;

            //UpdatePictureBoxPosition();
        }
Example #21
0
        /// <summary> Blob Detection
        /// This method for color object detection by Blob counter algorithm.
        /// If you using this method, then you can detecting as follows:
        ///             red circle, rectangle, triangle
        ///             blue circle, rectangle, triangle
        ///             green circle, rectangle, triangle
        /// the process of this method as follow:
        ///     1. color filtering by Euclidean filtering(R, G, B).
        ///     2. the grayscale filtering based on color filtered image.
        ///     3. In this step, you can choose the blur option. Applied blur option(or not),
        ///        this method donging Sobel edge filtering based on grayscale(or grayscale + blur) image.
        ///     4. the binary filtering based on edge filter image.
        ///     5. Finally, detecting object, distance from the camera and degree are expreed on picturebox 1.
        /// </summary>

        private Bitmap BlobDetection(Bitmap _bitmapSourceImage)
        {
            #region Color filtering by Euclidean filtering
            switch (iColorMode)
            {
            case 1:
                //_colorFilter.CenterColor = new RGB(230, 30, 30);
                iRedValue   = sbRedColor.Value;
                iBlueValue  = sbBlueColor.Value;
                iGreenValue = sbGreenColor.Value;

                _colorFilter.CenterColor = new RGB((byte)iRedValue, (byte)iGreenValue, (byte)iBlueValue);
                _colorFilter.Radius      = (short)iRadius;
                _colorFilterImage        = _colorFilter.Apply(_bitmapSourceImage);
                break;

            case 2:
                iRedValue   = sbRedColor.Value;
                iBlueValue  = sbBlueColor.Value;
                iGreenValue = sbGreenColor.Value;

                _colorFilter.CenterColor = new RGB((byte)iRedValue, (byte)iGreenValue, (byte)iBlueValue);
                _colorFilter.Radius      = (short)iRadius;
                _colorFilterImage        = _colorFilter.Apply(_bitmapSourceImage);
                break;

            case 3:
                iRedValue   = sbRedColor.Value;
                iBlueValue  = sbBlueColor.Value;
                iGreenValue = sbGreenColor.Value;

                _colorFilter.CenterColor = new RGB((byte)iRedValue, (byte)iGreenValue, (byte)iBlueValue);
                _colorFilter.Radius      = (short)iRadius;
                _colorFilterImage        = _colorFilter.Apply(_bitmapSourceImage);
                break;
            }
            #endregion

            Grayscale _grayscale = new Grayscale(0.2125, 0.7154, 0.0721);
            _bitmapGreyImage = _grayscale.Apply(_colorFilterImage);

            #region blur option with Edge filter
            //create a edge detector instance
            if (_blurFlag == true)
            {
                //Blur _blurfilter = new Blur();
                GaussianBlur _blurfilter = new GaussianBlur(1.5);
                _bitmapBlurImage = _blurfilter.Apply(_bitmapGreyImage);
                _bitmapEdgeImage = _edgeFilter.Apply(_bitmapBlurImage);
            }
            else if (_blurFlag == false)
            {
                _bitmapEdgeImage = _edgeFilter.Apply(_bitmapGreyImage);
            }
            #endregion

            Threshold _threshold = new Threshold(iThreshold);
            _bitmapBinaryImage = _threshold.Apply(_bitmapEdgeImage);

            ///
            /// blob counter algorithm initailze.
            /// BlobCounter.MinWidth and MinHeight -> for the defined minimum region
            ///
            BlobCounter _blobCounter = new BlobCounter();
            //Configure Filter
            _blobCounter.MinWidth    = 70;
            _blobCounter.MinHeight   = 70;
            _blobCounter.FilterBlobs = true;
            _blobCounter.ProcessImage(_bitmapBinaryImage);

            Blob[]             _blobPoints   = _blobCounter.GetObjectsInformation();
            Graphics           _g            = Graphics.FromImage(_bitmapSourceImage);
            SimpleShapeChecker _shapeChecker = new SimpleShapeChecker();

            for (int i = 0; i < _blobPoints.Length; i++)
            {
                List <IntPoint> _edgePoint = _blobCounter.GetBlobsEdgePoints(_blobPoints[i]);
                List <IntPoint> _corners   = null;
                AForge.Point    _center;
                float           _radius;
                //#region detecting Rectangle
                /////
                ///// _corners: the corner of Quadrilateral
                /////
                //if (_shapeChecker.IsQuadrilateral(_edgePoint, out _corners))
                //{
                //    //Drawing the reference point of the picturebox
                //    _g.DrawEllipse(_PictureboxPen, (float)(pictureBox1.Size.Width),
                //                                   (float)(pictureBox1.Size.Height),
                //                                   (float)10, (float)10);

                //    // Drawing setting for outline of detected object
                //    Rectangle[] _rects = _blobCounter.GetObjectsRectangles();
                //    System.Drawing.Point[] _coordinates = ToPointsArray(_corners);
                //    Pen _pen = new Pen(Color.Blue, ipenWidth);
                //    int _x = _coordinates[0].X;
                //    int _y = _coordinates[0].Y;

                //    // Drawing setting for centroid of detected object
                //    int _centroid_X = (int)_blobPoints[0].CenterOfGravity.X;
                //    int _centroid_Y = (int)_blobPoints[0].CenterOfGravity.Y;

                //    //Drawing the centroid point of object
                //    _g.DrawEllipse(_pen, (float)(_centroid_X), (float)(_centroid_Y), (float)10, (float)10);
                //    //Degree calculation
                //    int _deg_x = (int)_centroid_X - pictureBox1.Size.Width;
                //    int _deg_y = pictureBox1.Size.Height - (int)_centroid_Y;
                //    textBox1.Text = ("Degree: (" + _deg_x + ", " + _deg_y + ")");

                //    ///
                //    /// Drawing outline of detected object
                //    ///
                //    if (_coordinates.Length == 4)
                //    {
                //        string _shapeString = "" + _shapeChecker.CheckShapeType(_edgePoint);
                //        _g.DrawString(_shapeString, _font, _brush, _x, _y);
                //        _g.DrawPolygon(_pen, ToPointsArray(_corners));
                //    }

                //    //size of rectange
                //    foreach (Rectangle rc in _rects)
                //    {
                //        ///for debug
                //        //System.Diagnostics.Debug.WriteLine(
                //        //    string.Format("Rect size: ({0}, {1})", rc.Width, rc.Height));

                //        iFeatureWidth = rc.Width;
                //        //check the FindDistance method.
                //        double dis = FindDistance(iFeatureWidth);
                //        _g.DrawString(dis.ToString("N2") + "cm", _font, _brush, _x, _y + 60);
                //    }
                //}
                //#endregion

                #region detecting Circle
                ///
                /// _center: the center of circle
                /// _radius: the radius of circle
                ///
                if (_shapeChecker.IsCircle(_edgePoint, out _center, out _radius))
                {
                    //Drawing the reference point
                    _g.DrawEllipse(_PictureboxPen, (float)(pictureBox1.Size.Width),
                                   (float)(pictureBox1.Size.Height),
                                   (float)10, (float)10);

                    // Drawing setting for outline of detected object
                    Rectangle[] _rects       = _blobCounter.GetObjectsRectangles();
                    Pen         _pen         = new Pen(Color.Red, ipenWidth);
                    string      _shapeString = "" + _shapeChecker.CheckShapeType(_edgePoint);
                    int         _x           = (int)_center.X;
                    int         _y           = (int)_center.Y;
                    ///
                    /// Drawing outline of detected object
                    ///
                    _g.DrawString(_shapeString, _font, _brush, _x, _y);
                    _g.DrawEllipse(_pen, (float)(_center.X - _radius),
                                   (float)(_center.Y - _radius),
                                   (float)(_radius * 2),
                                   (float)(_radius * 2));

                    //Drawing the centroid point of object
                    int _centroid_X = (int)_blobPoints[0].CenterOfGravity.X;
                    int _centroid_Y = (int)_blobPoints[0].CenterOfGravity.Y;
                    _g.DrawEllipse(_pen, (float)(_centroid_X), (float)(_centroid_Y), (float)10, (float)10);
                    //Degree calculation
                    //int _deg_x = _centroid_X - pictureBox1.Size.Width;
                    //int _deg_y = pictureBox1.Size.Height - _centroid_Y;

                    float _deg_x = _center.X * 100 / pictureBox1.Image.Width;
                    float _deg_y = _center.Y * 100 / pictureBox1.Image.Height;
                    textBox2.Text = _deg_x + "";
                    textBox3.Text = _deg_y + "";
                    textBox1.Text = ("Degree: (" + _deg_x + ", " + _deg_y + ")");

                    //size of rectange
                    foreach (Rectangle rc in _rects)
                    {
                        ///for debug
                        //System.Diagnostics.Debug.WriteLine(
                        //    string.Format("Circle size: ({0}, {1})", rc.Width, rc.Height));
                        iFeatureWidth = rc.Width;
                        double dis = FindDistance(iFeatureWidth);
                        _g.DrawString(dis.ToString("N2") + "cm", _font, _brush, _x, _y + 60);
                    }
                }
                #endregion

                //#region detecting Triangle
                /////
                ///// _corners: the corner of Triangle
                /////
                //if (_shapeChecker.IsTriangle(_edgePoint, out _corners))
                //{
                //    //Drawing the reference point
                //    _g.DrawEllipse(_PictureboxPen, (float)(pictureBox1.Size.Width),
                //                                   (float)(pictureBox1.Size.Height),
                //                                   (float)10, (float)10);

                //    // Drawing setting for outline of detected object
                //    Rectangle[] _rects = _blobCounter.GetObjectsRectangles();
                //    Pen _pen = new Pen(Color.Green, ipenWidth);
                //    string _shapeString = "" + _shapeChecker.CheckShapeType(_edgePoint);
                //    int _x = (int)_center.X;
                //    int _y = (int)_center.Y;

                //    // Drawing setting for centroid of detected object
                //    int _centroid_X = (int)_blobPoints[0].CenterOfGravity.X;
                //    int _centroid_Y = (int)_blobPoints[0].CenterOfGravity.Y;
                //    ///
                //    /// Drawing outline of detected object
                //    ///
                //    _g.DrawString(_shapeString, _font, _brush, _x, _y);
                //    _g.DrawPolygon(_pen, ToPointsArray(_corners));

                //    //Drawing the centroid point of object
                //    _g.DrawEllipse(_pen, (float)(_centroid_X), (float)(_centroid_Y), (float)10, (float)10);
                //    //Degree calculation
                //    int _deg_x = (int)_centroid_X - pictureBox1.Size.Width;
                //    int _deg_y = pictureBox1.Size.Height - (int)_centroid_Y;
                //    textBox1.Text = ("Degree: (" + _deg_x + ", " + _deg_y + ")");
                //    //size of rectange
                //    foreach (Rectangle rc in _rects)
                //    {
                //        ///for debug
                //        //System.Diagnostics.Debug.WriteLine(
                //        //    string.Format("Triangle Size: ({0}, {1})", rc.Width, rc.Height));

                //        iFeatureWidth = rc.Width;
                //        double dis = FindDistance(iFeatureWidth);
                //        _g.DrawString(dis.ToString("N2") + "cm", _font, _brush, _x, _y + 60);
                //    }
                //}
                //#endregion
            }
            return(_bitmapSourceImage);
        }
Example #22
0
        public void findObjects(Bitmap image1, Bitmap image2) //find object(s)
        {
            BlobCounter blobCounter1 = new BlobCounter();

            blobCounter1.MinWidth     = 5;
            blobCounter1.MinHeight    = 5;
            blobCounter1.FilterBlobs  = true;
            blobCounter1.ObjectsOrder = ObjectsOrder.Size;

            //----------------------------------

            BlobCounter blobCounter2 = new BlobCounter();

            blobCounter2.MinWidth     = 5;
            blobCounter2.MinHeight    = 5;
            blobCounter2.FilterBlobs  = true;
            blobCounter2.ObjectsOrder = ObjectsOrder.Size;

            BitmapData objectsData1 = image1.LockBits(new Rectangle(0, 0, image1.Width, image1.Height), ImageLockMode.ReadOnly, image1.PixelFormat);
            // grayscaling
            Grayscale      grayscaleFilter1 = new Grayscale(0.2125, 0.7154, 0.0721);
            UnmanagedImage grayImage1       = grayscaleFilter1.Apply(new UnmanagedImage(objectsData1));

            // unlock image
            image1.UnlockBits(objectsData1);

            BitmapData objectsData2 = image1.LockBits(new Rectangle(0, 0, image1.Width, image1.Height), ImageLockMode.ReadOnly, image1.PixelFormat);
            // grayscaling
            Grayscale      grayscaleFilter2 = new Grayscale(0.2125, 0.7154, 0.0721);
            UnmanagedImage grayImage2       = grayscaleFilter2.Apply(new UnmanagedImage(objectsData2));

            // unlock image
            image1.UnlockBits(objectsData2);


            blobCounter1.ProcessImage(image1);
            Rectangle[] rects1 = blobCounter1.GetObjectsRectangles();
            Blob[]      blobs1 = blobCounter1.GetObjectsInformation();

            blobCounter2.ProcessImage(image2);
            Rectangle[] rects2 = blobCounter2.GetObjectsRectangles();
            Blob[]      blobs2 = blobCounter2.GetObjectsInformation();

            if (rdiobtnsingleobject.Checked)
            {
                //Single object Tracking--------
                Graphics g = pictureBox1.CreateGraphics();
                if (rects1.Length > 0)
                {
                    Rectangle objectRect1 = rects1[0];
                    using (Pen pen = new Pen(Color.FromArgb(252, 3, 26), 2))
                    {
                        g.DrawRectangle(pen, objectRect1);
                    }
                }
                if (rects2.Length > 0)
                {
                    Rectangle objectRect2 = rects2[0];
                    using (Pen pen = new Pen(Color.FromArgb(252, 3, 26), 2))
                    {
                        g.DrawRectangle(pen, objectRect2);
                    }
                }
                g.Dispose();
            }



            if (rdiobtnMultipleObjects.Checked)
            {
                //Multi tracking-------
                for (int i = 0; rects1.Length > i; i++)
                {
                    Rectangle objectRect = rects1[i];
                    Graphics  g          = pictureBox1.CreateGraphics();
                    using (Pen pen = new Pen(Color.FromArgb(252, 3, 26), 2))
                    {
                        g.DrawRectangle(pen, objectRect);
                        g.DrawString((i + 1).ToString(), new Font("Arial", 12), Brushes.Red, objectRect);
                    }
                    int objectX = objectRect.X + (objectRect.Width / 2);
                    int objectY = objectRect.Y + (objectRect.Height / 2);
                    g.Dispose();
                }
            }

            if (rdiobtnGeoShape.Checked)
            {
                SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

                int circles   = 0;
                int squares   = 0;
                int triangles = 0;

                Graphics g         = pictureBox1.CreateGraphics();
                Pen      yellowPen = new Pen(Color.Yellow, 2); // circles
                Pen      redPen    = new Pen(Color.Red, 2);    // quadrilateral
                Pen      brownPen  = new Pen(Color.Brown, 2);  // quadrilateral with known sub-type
                Pen      greenPen  = new Pen(Color.Green, 2);  // known triangle
                Pen      bluePen   = new Pen(Color.Blue, 2);   // triangle
                for (int i = 0, n = blobs1.Length; i < n; i++)
                {
                    List <IntPoint> edgePoints = blobCounter1.GetBlobsEdgePoints(blobs1[i]);
                    AForge.Point    center;
                    float           radius;

                    // is circle ?
                    if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                    {
                        g.DrawEllipse(yellowPen,
                                      (float)(center.X - radius), (float)(center.Y - radius),
                                      (float)(radius * 2), (float)(radius * 2));
                        circles++;
                    }
                    else
                    {
                        List <IntPoint> corners;

                        // is triangle or quadrilateral
                        if (shapeChecker.IsConvexPolygon(edgePoints, out corners))
                        {
                            // get sub-type
                            PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners);

                            Pen pen;

                            if (subType == PolygonSubType.Unknown)
                            {
                                if (corners.Count == 4)
                                {
                                    pen = redPen;
                                }
                                else
                                {
                                    pen = bluePen;
                                    triangles++;
                                }
                            }
                            else
                            {
                                if (corners.Count == 4)
                                {
                                    pen = brownPen;
                                    squares++;
                                }
                                else
                                {
                                    pen = greenPen;
                                    triangles++;
                                }
                            }

                            g.DrawPolygon(pen, ToPointsArray(corners));
                        }
                    }
                }
                g.DrawString("circles: " + circles.ToString() + " squares: " + squares.ToString() + " triangles: " + triangles.ToString(), new Font("Arial", 12), Brushes.Red, new System.Drawing.Point(0, 0));
                triangles = 0;
                circles   = 0;
                squares   = 0;
                yellowPen.Dispose();
                redPen.Dispose();
                greenPen.Dispose();
                bluePen.Dispose();
                brownPen.Dispose();
                g.Dispose();
            }
        }
Example #23
0
        private void reader_IRFrameArrived(object sender, MultiSourceFrameArrivedEventArgs e)
        {
            var reference = e.FrameReference.AcquireFrame();

            using (InfraredFrame frame = reference.InfraredFrameReference.AcquireFrame())
            {
                if (frame != null)
                {
                    int      width     = frame.FrameDescription.Width;
                    int      height    = frame.FrameDescription.Height;
                    ushort[] data      = new ushort[width * height];
                    byte[]   pixelData = new byte[width * height * 4];


                    frame.CopyFrameDataToArray(data);
                    Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb);
                    for (int infraredIndex = 0; infraredIndex < data.Length; infraredIndex++)
                    {
                        ushort ir        = data[infraredIndex];
                        byte   intensity = (byte)(ir >> 8);

                        pixelData[infraredIndex * 4]     = intensity; // Blue
                        pixelData[infraredIndex * 4 + 1] = intensity; // Green
                        pixelData[infraredIndex * 4 + 2] = intensity; // Red
                        pixelData[infraredIndex * 4 + 3] = 255;       //Brightness
                    }
                    var bitmapdata = bitmap.LockBits(
                        new Rectangle(0, 0, width, height),
                        ImageLockMode.WriteOnly,
                        bitmap.PixelFormat
                        );
                    IntPtr ptr = bitmapdata.Scan0;

                    Marshal.Copy(pixelData, 0, ptr, pixelData.Length);
                    bitmap.UnlockBits(bitmapdata);
                    bitmap.RotateFlip(RotateFlipType.Rotate180FlipY);

                    counter = new BlobCounter();
                    EuclideanColorFiltering filter  = new EuclideanColorFiltering();
                    ResizeNearestNeighbor   filter2 = new ResizeNearestNeighbor(1920, 1080);
                    filter.CenterColor = new RGB(Color.White); //Pure White
                    filter.FillOutside = false;
                    filter.FillColor   = new RGB(Color.White); //Replacement Color

                    bmp = filter.Apply(bitmap);

                    filter2.Apply(bmp);

                    counter.BackgroundThreshold = Color.Gray;
                    counter.ProcessImage(bmp);
                    Blob[]             blobs        = counter.GetObjectsInformation();
                    Pen                redPen       = new Pen(Color.Red, 20);//Kreisradius
                    Graphics           g            = Graphics.FromImage(bmp);
                    SimpleShapeChecker shapeChecker = new SimpleShapeChecker();


                    for (int i = 0; i < blobs.Length; i++)
                    {
                        List <IntPoint> edgePoints = counter.GetBlobsEdgePoints(blobs[i]);

                        AForge.Point center;
                        float        radius;

                        if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                        {
                            g.DrawEllipse(redPen,
                                          (int)(center.X - radius),
                                          (int)(center.Y - radius),
                                          (int)(radius * 2),
                                          (int)(radius * 2));
                            if (i == 1)
                            {
                                ecken1_x = (int)center.X;
                                ecken1_y = (int)center.Y;
                            }
                            if (i == 2)
                            {
                                ecken2_x = (int)center.X;
                                ecken2_y = (int)center.Y;
                            }
                            if (i == 3)
                            {
                                ecken3_x = (int)center.X;
                                ecken3_y = (int)center.Y;
                            }
                            if (i == 4)
                            {
                                ecken4_x = (int)center.X;
                                ecken4_y = (int)center.Y;
                            }
                        }
                    }
                }
            }
        }
Example #24
0
        // Process image
        private void ProcessImage(Bitmap bitmap)
        {
            // lock image
            var bitmapData = bitmap.LockBits(
                new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                ImageLockMode.ReadWrite, bitmap.PixelFormat);

            // step 1 - turn background to black
            var colorFilter = new ColorFiltering
            {
                Red              = new IntRange(0, 64),
                Green            = new IntRange(0, 64),
                Blue             = new IntRange(0, 64),
                FillOutsideRange = false
            };

            colorFilter.ApplyInPlace(bitmapData);

            // step 2 - locating objects
            var blobCounter = new BlobCounter
            {
                FilterBlobs = true,
                MinHeight   = 5,
                MinWidth    = 5
            };

            blobCounter.ProcessImage(bitmapData);
            var blobs = blobCounter.GetObjectsInformation();

            bitmap.UnlockBits(bitmapData);

            // step 3 - check objects' type and highlight
            var shapeChecker = new SimpleShapeChecker();

            var g         = Graphics.FromImage(bitmap);
            var yellowPen = new Pen(Color.Yellow, 2);            // circles
            var redPen    = new Pen(Color.Red, 2);               // quadrilateral
            var brownPen  = new Pen(Color.Brown, 2);             // quadrilateral with known sub-type
            var greenPen  = new Pen(Color.Green, 2);             // known triangle
            var bluePen   = new Pen(Color.Blue, 2);              // triangle

            for (int i = 0, n = blobs.Length; i < n; i++)
            {
                var edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);

                AForge.Point center;
                float        radius;

                // is circle ?
                if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                {
                    g.DrawEllipse(yellowPen,
                                  (float)(center.X - radius), (float)(center.Y - radius),
                                  (float)(radius * 2), (float)(radius * 2));
                }
                else
                {
                    List <IntPoint> corners;

                    // is triangle or quadrilateral
                    if (shapeChecker.IsConvexPolygon(edgePoints, out corners))
                    {
                        // get sub-type
                        var subType = shapeChecker.CheckPolygonSubType(corners);

                        Pen pen;

                        if (subType == PolygonSubType.Unknown)
                        {
                            pen = (corners.Count == 4) ? redPen : bluePen;
                        }
                        else
                        {
                            pen = (corners.Count == 4) ? brownPen : greenPen;
                        }

                        g.DrawPolygon(pen, ToPointsArray(corners));
                    }
                }
            }

            yellowPen.Dispose();
            redPen.Dispose();
            greenPen.Dispose();
            bluePen.Dispose();
            brownPen.Dispose();
            g.Dispose();

            // put new image to clipboard
            Clipboard.SetDataObject(bitmap);
            // and to picture box
            pictureBox.Image = bitmap;

            UpdatePictureBoxPosition();
        }
Example #25
0
        private void altProcess(Bitmap bm, int level)
        {
            var img = new Image <Bgr, byte>(bm);

            if (level == 1)
            {
                var resImage = new Image <Bgr, byte>(img.Bitmap);
                CvInvoke.BilateralFilter(resImage, img, 30, 80, 80);
                CvInvoke.MedianBlur(img, img, 5);
                resImage = img;
            }
            else if (level == 2)
            {
                CvInvoke.MedianBlur(img, img, 5);
                var resImage = new Image <Bgr, byte>(img.Bitmap);
                CvInvoke.BilateralFilter(resImage, img, 25, 75, 75);
                CvInvoke.Blur(img, img, new Size(5, 5), new Point(0, 0));
            }

            var grayimage = new Image <Gray, byte>(bm);

            CvInvoke.CvtColor(img, grayimage, ColorConversion.Bgr2Gray);

            BlackBG(grayimage);

            Console.WriteLine("Filtering done");

            var cannyThreshold = GetKMeansThreshold(grayimage);

            label2.Text = cannyThreshold.ToString();

            Thresholding(grayimage, cannyThreshold);

            Console.WriteLine("Canny threshold using KMEANS found " + cannyThreshold);

            //Convert the image to grayscale and filter out the noise

            var cannyEdges = new UMat();

            Console.WriteLine("Canny threshold using KMEANS found " + cannyThreshold);

            var uimage = new UMat();

            CvInvoke.CvtColor(img, uimage, ColorConversion.Bgr2Gray);

            CvInvoke.Canny(uimage, cannyEdges, cannyThreshold, cannyThreshold);

            BlobCounter blobCounter = new BlobCounter( );

            if (level == 1)
            {
                blobCounter.FilterBlobs = true;
                blobCounter.MinHeight   = 25;
                blobCounter.MinWidth    = 25;
                blobCounter.ProcessImage(cannyEdges.Bitmap);
            }
            else
            {
                blobCounter.ProcessImage(grayimage.ToBitmap());
            }
            //blobCounter.ProcessImage(grayimage.ToBitmap());

            Blob[] blobs = blobCounter.GetObjectsInformation( );

            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();


            var      triangleList = new List <Triangle2DF>();
            var      boxList      = new List <RotatedRect>();
            var      circleList   = new List <CircleF>();
            Bitmap   newBM        = new Bitmap(img.Bitmap);
            Graphics g            = Graphics.FromImage(newBM);
            Pen      redPen       = new Pen(Color.Red, 2);


            Pen yellowPen = new Pen(Color.Yellow, 2);
            Pen greenPen  = new Pen(Color.Green, 2);
            Pen bluePen   = new Pen(Color.Blue, 2);

            for (int i = 0, n = blobs.Length; i < n; i++)
            {
                List <IntPoint> edgePoints =
                    blobCounter.GetBlobsEdgePoints(blobs[i]);

                AForge.Point center;
                float        radius;

                if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                {
                    //g.DrawEllipse(bluePen,
                    //    (float)(center.X - radius), (float)(center.Y - radius),
                    //    (float)(radius * 2), (float)(radius * 2));
                    circleList.Add(new CircleF(new PointF(center.X, center.Y), radius));
                }
                else
                {
                    List <IntPoint> corners;
                    if (edgePoints.Count > 1)
                    {
                        if (shapeChecker.IsQuadrilateral(edgePoints, out corners))
                        {
                            System.Console.WriteLine(corners.Count);
                            if (shapeChecker.CheckPolygonSubType(corners) ==
                                PolygonSubType.Square || shapeChecker.CheckPolygonSubType(corners) ==
                                PolygonSubType.Rectangle)
                            {
                                IntPoint minXY, maxXY;

                                PointsCloud.GetBoundingRectangle(corners, out minXY, out maxXY);
                                AForge.Point c = PointsCloud.GetCenterOfGravity(corners);
                                //g.DrawPolygon(greenPen, ToPointsArray(corners));
                                boxList.Add(new RotatedRect(new PointF(c.X, c.Y), new SizeF(maxXY.X - minXY.X, maxXY.Y - minXY.Y), 0));
                            }
                        }
                        else
                        {
                            corners = PointsCloud.FindQuadrilateralCorners(edgePoints);
                            if (corners.Count == 3)
                            {
                                Triangle2DF tri = new Triangle2DF(new PointF(corners[0].X, corners[0].Y), new PointF(corners[1].X, corners[1].Y), new PointF(corners[2].X, corners[2].Y));
                                triangleList.Add(tri);
                                //g.DrawPolygon(yellowPen, ToPointsArray(corners));
                            }
                            //g.DrawPolygon(redPen, ToPointsArray(corners));
                        }
                    }
                }
            }
            Console.WriteLine("boxes " + boxList.Count);
            Console.WriteLine("triangles " + triangleList.Count);
            Console.WriteLine("circles " + circleList.Count);

            redPen.Dispose();
            greenPen.Dispose();
            bluePen.Dispose();
            yellowPen.Dispose();
            //g.Dispose();
            resPicBox.Image = newBM;
            CircleF[] circles = circleList.ToArray();
            var       cList   = circles.ToList();

            FilterSame(boxList, triangleList, cList, img.Width * img.Height);
            circles = cList.ToArray();
            var points = new List <PointF>();

            var Image = img.CopyBlank();

            foreach (var triangle in triangleList)
            {
                Image.Draw(triangle, new Bgr(Color.Red), 3);
                points.Add(triangle.Centeroid);
            }

            foreach (var box in boxList)
            {
                Image.Draw(box, new Bgr(Color.Blue), 3);
                points.Add(box.Center);
            }

            foreach (var circle in circles)
            {
                Image.Draw(circle, new Bgr(Color.DarkCyan), 3);
                points.Add(circle.Center);
            }

            var listPoints = SortPoints(points, img);

            for (var i = 0; i < listPoints.Length; i++)
            {
                Console.WriteLine(listPoints[i].X.ToString() + " " + listPoints[i].Y.ToString());
            }

            System.Console.WriteLine("Points sorted, num of objects " + listPoints.Length.ToString());
            resPicBox.Image = (Image + img).ToBitmap();
            if (listPoints.Length > 3)
            {
                var bezSegList = InterpolatePointWithBeizerCurves(listPoints.ToList <PointF>());
                var gr         = Graphics.FromImage(resPicBox.Image);
                var p          = new Pen(Color.Red);

                foreach (BeizerCurveSegment seg in bezSegList)
                {
                    var bezierList = GetBez(new PointF[]
                                            { seg.StartPoint, seg.FirstControlPoint, seg.SecondControlPoint, seg.EndPoint });
                    for (var i = 0; i < bezierList.Length - 1; i++)
                    {
                        gr.DrawLine(p, bezierList[i], bezierList[i + 1]);
                    }
                }
            }
            else
            {
                var gr = Graphics.FromImage(resPicBox.Image);
                var p  = new Pen(Color.Red);

                for (var i = 0; i < listPoints.Length - 1; i++)
                {
                    gr.DrawLine(p, listPoints[i], listPoints[i + 1]);
                }
            }

            //var bezierList = GetBezierCurve1(listPoints);
        }
Example #26
0
        public void ProcessImage(Bitmap bitmap)
        {
            // lock image
            BitmapData bitmapData = bitmap.LockBits(
                new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                ImageLockMode.ReadWrite, bitmap.PixelFormat);

            // step 1 - turn background to black
            ColorFiltering colorFilter = new ColorFiltering();

            // coin.jpg had these boundaries: red <0,64>, green <0,64>, blue <0,64>
            colorFilter.Red              = new IntRange(redBounds[0], redBounds[1]);
            colorFilter.Green            = new IntRange(greenBounds[0], greenBounds[1]);
            colorFilter.Blue             = new IntRange(blueBounds[0], blueBounds[1]);
            colorFilter.FillOutsideRange = false;
            colorFilter.ApplyInPlace(bitmapData);

            // step 2 - locating objects
            BlobCounter blobCounter = new BlobCounter();

            blobCounter.FilterBlobs = true;
            blobCounter.MinHeight   = 10;
            blobCounter.MinWidth    = 10;
            blobCounter.ProcessImage(bitmapData);
            Blob[] blobs = blobCounter.GetObjectsInformation();
            bitmap.UnlockBits(bitmapData);

            // step 3 - check objects' type and highlight
            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();
            Graphics           g            = Graphics.FromImage(bitmap);
            Pen circlePen       = new Pen(Color.Yellow, 2); // circles
            Pen strangeShapePen = new Pen(Color.Red, 2);    // quadrilateral with unknown sub-type
            Pen rectanglePen    = new Pen(Color.Brown, 2);  // quadrilateral with known sub-type
            Pen trianglePen     = new Pen(Color.Blue, 2);   // triangle

            // step 3.5 - prepare file to save obstacles
            string       path   = @"C:\Users\Robert\Documents\Visual Studio 2015\Projects\SMTMotionPlanning\SMTMotionPlanning\obstacleFiles\";
            FileStream   stream = new FileStream(path + "obstacles.txt", FileMode.Create, FileAccess.Write);
            StreamWriter writer = new StreamWriter(stream);

            for (int i = 0, n = blobs.Length; i < n; i++)
            {
                List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);
                edgePoints = eliminateDuplicates(edgePoints);
                AForge.Point    center;
                List <IntPoint> corners;
                float           radius;
                if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                {
                    g.DrawEllipse(circlePen, center.X - radius, center.Y - radius, 2 * radius, 2 * radius);
                    writer.WriteLine("e " + (int)(center.X - radius) + " " + (int)(center.Y - radius)
                                     + " " + (int)(radius) + " " + (int)(radius));
                }
                else if (shapeChecker.IsConvexPolygon(edgePoints, out corners))
                {
                    PolygonSubType polygonType = shapeChecker.CheckPolygonSubType(corners);
                    Pen            pen;
                    if (polygonType == PolygonSubType.Rectangle || polygonType == PolygonSubType.Square)
                    {
                        pen = rectanglePen;
                        writer.WriteLine("r " + corners[0].X + " " + corners[0].Y + " " +
                                         Math.Abs(corners[0].X - corners[1].X) + " " + Math.Abs(corners[0].Y - corners[2].Y));
                        g.DrawPolygon(pen, ToPointsArray(corners));
                    }
                    else
                    {
                        pen = corners.Count == 3 ? trianglePen : strangeShapePen;
                        g.DrawPolygon(pen, ToPointsArray(corners));
                        writer.Write("p");
                        foreach (IntPoint corner in corners)
                        {
                            writer.Write(" " + corner.X + " " + corner.Y);
                        }
                        writer.WriteLine();
                    }
                }
                else
                {
                    corners = orderPolygonCorners(findPolygonCorners(edgePoints), edgePoints);
                    g.DrawPolygon(strangeShapePen, ToPointsArray(corners));
                    writer.Write("p");
                    foreach (IntPoint corner in corners)
                    {
                        writer.Write(" " + corner.X + " " + corner.Y);
                    }
                    writer.WriteLine();
                }
            }

            circlePen.Dispose();
            strangeShapePen.Dispose();
            trianglePen.Dispose();
            rectanglePen.Dispose();
            writer.Close();
            stream.Close();
            g.Dispose();
            rescaleCoordinates();
            transformCoordinates();
        }
Example #27
0
        private void ProcessImage(Bitmap bitmap)
        {
            // reset counters
            numberOfCircleShits   = 0;
            numberOfLineShits     = 0;
            numberOfSquareShits   = 0;
            numberOfTriangleShits = 0;

            // lock image
            BitmapData bitmapData = bitmap.LockBits(
                new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                ImageLockMode.ReadWrite, bitmap.PixelFormat);

            // step 1 - turn background to black
            ColorFiltering colorFilter = new ColorFiltering();

            colorFilter.Red              = new IntRange(0, 64);
            colorFilter.Green            = new IntRange(0, 64);
            colorFilter.Blue             = new IntRange(0, 64);
            colorFilter.FillOutsideRange = false;

            colorFilter.ApplyInPlace(bitmapData);

            // step 2 - locating objects
            BlobCounter blobCounter = new BlobCounter();

            blobCounter.FilterBlobs = true;
            blobCounter.MinHeight   = 5;
            blobCounter.MinWidth    = 5;

            blobCounter.ProcessImage(bitmapData);
            Blob[] blobs = blobCounter.GetObjectsInformation();
            bitmap.UnlockBits(bitmapData);

            // step 3 - check objects' type and highlight
            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

            Graphics g = Graphics.FromImage(bitmap);

            for (int i = 0, n = blobs.Length; i < n; i++)
            {
                List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);

                AForge.Point center;
                float        radius;

                // is circle ?
                if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                {
                    numberOfCircleShits++;
                }
                else
                {
                    List <IntPoint> corners;

                    // is triangle or quadrilateral
                    if (shapeChecker.IsConvexPolygon(edgePoints, out corners))
                    {
                        // get sub-type
                        PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners);
                        Pen            pen;
                        if (subType == PolygonSubType.Square)
                        {
                            numberOfSquareShits++;
                        }
                        else if (subType == PolygonSubType.EquilateralTriangle)
                        {
                            numberOfTriangleShits++;
                        }
                        else
                        {
                            numberOfLineShits++;
                        }
                    }
                }
            }
            g.Dispose();
            // put new image to clipboard
            Clipboard.SetDataObject(bitmap);
            // and to picture box
            picture.Image       = bitmap;
            triangleCount.Text  = "" + numberOfTriangleShits;
            CircleCount.Text    = "" + numberOfCircleShits;
            SquareCount.Text    = "" + numberOfSquareShits;
            RectangleCount.Text = "" + +numberOfLineShits;
        }
Example #28
0
        /// <summary>
        ///     Performs the analysis on the image
        /// </summary>
        public void Analyze(bool thorough = true)
        {
            if (m_disposed)
            {
                throw new ObjectDisposedException("ImageProcessor");
            }

            if (IsScannable)
            {
                return;
            }

            LuminanceSource source    = new BitmapLuminanceSource(m_bitmap);
            var             binarizer = new HybridBinarizer(source);
            var             binBitmap = new BinaryBitmap(binarizer);

            // Try to extract the form data
            var barReader = new BarcodeReader();

            barReader.AutoRotate              = true;
            barReader.Options.TryHarder       = thorough;
            barReader.Options.PossibleFormats = new List <BarcodeFormat> {
                BarcodeFormat.CODE_128
            };

            m_barcodeResults = barReader.DecodeMultiple(source);

            // Look for barcode markers if possible
            if (m_barcodeResults != null)
            {
                MarkerCodes = m_barcodeResults.Where(o => o.Text.StartsWith("OMR:")).ToArray();
            }
            IsScannable = true;
            // Get the template data
            var markerCode = MarkerCodes == null
                ? null
                : MarkerCodes.FirstOrDefault(o => o.Text.StartsWith("OMR:TL") || o.Text.StartsWith("OMR:ID"));

            // Get the guiding points by circles
            var grayFilter      = new GrayscaleY();
            var thresholdFilter = new Threshold(127);
            var invertFilter    = new Invert();

            using (var searchImage = invertFilter.Apply(thresholdFilter.Apply(grayFilter.Apply(m_bitmap))))
            {
                // Blobs
                var blobCounter = new BlobCounter();
                blobCounter.FilterBlobs = true;
                blobCounter.MinHeight   = 30;
                blobCounter.MinWidth    = 30;

                // Check for circles
                blobCounter.ProcessImage(searchImage);
                var blobs         = blobCounter.GetObjectsInformation();
                var shapeChecker  = new SimpleShapeChecker();
                var controlPoints = new List <Point>();
                var currentCheck  = 45;
                while ((currentCheck-- > 20) && (controlPoints.Count != 4))
                {
                    controlPoints.Clear();
                    // Get the positions
                    foreach (var blob in blobs)
                    {
                        var   center = new Point();
                        float radius = 0;

                        if (shapeChecker.IsCircle(blobCounter.GetBlobsEdgePoints(blob), out center, out radius) &&
                            (radius > currentCheck))
                        {
                            controlPoints.Add(center);
                        }
                    }
                }

                // Control points
                IsScannable &= controlPoints.Count == 4;
                if (!IsScannable)
                {
                    return;
                }

                // Now set markers
                m_topLeft     = controlPoints[0]; //new AForge.Point(this.m_bitmap.Width + 10, this.m_bitmap.Height + 10);
                m_topRight    = controlPoints[1];
                m_bottomLeft  = controlPoints[2];
                m_bottomRight = controlPoints[3];

                // Find the right most bubble
                float rightMost = controlPoints.Select(o => o.X).Max(),
                      leftMost  = controlPoints.Select(o => o.X).Min();
                // Organize those that are left/right
                Point[] lefties = controlPoints.Where(o => o.X < leftMost + (rightMost - leftMost) / 2).ToArray(),
                righties = controlPoints.Where(o => o.X > leftMost + (rightMost - leftMost) / 2).ToArray();

                // HACK:
                if (lefties[0].Y < lefties[1].Y)
                {
                    m_topLeft    = lefties[0];
                    m_bottomLeft = lefties[1];
                }
                else
                {
                    m_topLeft    = lefties[1];
                    m_bottomLeft = lefties[0];
                }

                // HACK:
                if (righties[0].Y < righties[1].Y)
                {
                    m_topRight    = righties[0];
                    m_bottomRight = righties[1];
                }
                else
                {
                    m_topRight    = righties[1];
                    m_bottomRight = righties[0];
                }
            }

            if (!IsScannable)
            {
                return;
            }

            // Get the template data
            if ((MarkerCodes != null) && (markerCode != null))
            {
                var templateData = markerCode.Text.Split(':');
                if (templateData.Length > 2)
                {
                    TemplateName = templateData[2];
                    if (templateData.Length > 3)
                    {
                        Parameters = templateData.Skip(3).ToArray();
                    }
                }
            }
        }
Example #29
0
        public void nesnebul(Bitmap image)
        {
            BlobCounter blobCounter = new BlobCounter();

            blobCounter.MinWidth     = 5;
            blobCounter.MinHeight    = 5;
            blobCounter.FilterBlobs  = true;
            blobCounter.ObjectsOrder = ObjectsOrder.Size;
            //Grayscale griFiltre = new Grayscale(0.2125, 0.7154, 0.0721);
            //Grayscale griFiltre = new Grayscale(0.2, 0.2, 0.2);
            //Bitmap griImage = griFiltre.Apply(image);

            BitmapData objectsData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, image.PixelFormat);
            // grayscaling
            Grayscale      grayscaleFilter = new Grayscale(0.2125, 0.7154, 0.0721);
            UnmanagedImage grayImage       = grayscaleFilter.Apply(new UnmanagedImage(objectsData));

            // unlock image
            image.UnlockBits(objectsData);


            blobCounter.ProcessImage(image);
            Rectangle[] rects = blobCounter.GetObjectsRectangles();
            Blob[]      blobs = blobCounter.GetObjectsInformation();
            pictureBox2.Image = image;



            if (radio_single_object_track.Checked)
            {
                //Single Object Tracking Single Tracking--------

                foreach (Rectangle recs in rects)
                {
                    if (rects.Length > 0)
                    {
                        Rectangle objectRect = rects[0];
                        //Graphics g = Graphics.FromImage(image);
                        Graphics g  = pictureBox1.CreateGraphics();
                        Graphics g2 = pictureBox2.CreateGraphics();
                        using (Pen pen = new Pen(Color.FromArgb(252, 3, 26), 2))
                        {
                            g.DrawRectangle(pen, objectRect);
                        }
                        //Coordinates of the rectified rectangle are taken.
                        int objectX = objectRect.X + (objectRect.Width / 2);
                        int objectY = objectRect.Y + (objectRect.Height / 2);
                        g.DrawString(objectX.ToString() + "X" + objectY.ToString(), new Font("Arial", 12), Brushes.Red, new System.Drawing.Point(250, 1));
                        Rectangle rec = new Rectangle(objectX, objectY, 5, 5);
                        g2.DrawEllipse(Pens.White, rec);
                        g.Dispose();

                        if (chek_show_coordi.Checked)
                        {
                            this.Invoke((MethodInvoker) delegate
                            {
                                richTextBox1.Text = objectRect.Location.ToString() + "\n" + richTextBox1.Text + "\n";;
                            });
                        }
                    }
                }
            }



            if (radio_multi_obj_track.Checked)
            {
                //Multi tracking Çoklu cisim Takibi-------

                for (int i = 0; rects.Length > i; i++)
                {
                    Rectangle objectRect = rects[i];
                    //Graphics g = Graphics.FromImage(image);
                    Graphics g = pictureBox1.CreateGraphics();
                    using (Pen pen = new Pen(Color.FromArgb(252, 3, 26), 2))
                    {
                        g.DrawRectangle(pen, objectRect);
                        g.DrawString((i + 1).ToString(), new Font("Arial", 12), Brushes.Red, objectRect);
                    }
                    //Cizdirilen Dikdörtgenin Koordinatlari aliniyor.
                    int objectX = objectRect.X + (objectRect.Width / 2);
                    int objectY = objectRect.Y + (objectRect.Height / 2);
                    g.DrawString(objectX.ToString() + "X" + objectY.ToString(), new Font("Arial", 12), Brushes.Red, new System.Drawing.Point(250, 1));


                    if (chck_dis_meter.Checked)
                    {
                        if (rects.Length > 1)
                        {
                            for (int j = 0; j < rects.Length - 1; j++)
                            {
                                int ilkx = (rects[j].Right + rects[j].Left) / 2;
                                int ilky = (rects[j].Top + rects[j].Bottom) / 2;

                                int ikix = (rects[j + 1].Right + rects[j + 1].Left) / 2;
                                int ikiy = (rects[j + 1].Top + rects[j + 1].Bottom) / 2;

                                g = pictureBox1.CreateGraphics();
                                g.DrawLine(Pens.Red, rects[j].Location, rects[j + 1].Location);
                                g.DrawLine(Pens.Blue, rects[0].Location, rects[rects.Length - 1].Location);
                                g.DrawLine(Pens.Red, ilkx, ilky, ikix, ikiy);
                            }
                        }

                        if (rects.Length == 2)
                        {
                            Rectangle ilk = rects[0];
                            Rectangle iki = rects[1];

                            int ilkX = ilk.X + (ilk.Width / 2);
                            int ilkY = ilk.Y + (ilk.Height / 2);

                            int ikiX = iki.X + (iki.Width / 2);
                            int ikiY = iki.Y + (iki.Height / 2);

                            //1 pixel (X) = 0.0264583333333334 centimeter [cm]

                            double formul = Math.Floor((Math.Sqrt((Math.Pow((ilkX - ikiX), 2)) + Math.Pow((ilkY - ikiY), 2))) * 0.0264);

                            string uzaklikY = "Y-" + Convert.ToString(ilkX - ikiX);
                            string uzaklikX = "X-" + Convert.ToString(ilkY - ikiY);

                            string distance = uzaklikX + " " + uzaklikY;

                            AForge.Imaging.Drawing.Line(objectsData, new IntPoint((int)ilkX, (int)ilkY), new IntPoint((int)ikiX, (int)ikiY), Color.Blue);


                            this.Invoke((MethodInvoker) delegate
                            {
                                richTextBox2.Text = formul.ToString() + " cm\n" + richTextBox2.Text + " cm\n";;
                            });


                            if (check_dist_coord.Checked)
                            {
                                this.Invoke((MethodInvoker) delegate
                                {
                                    richTextBox3.Text = distance.ToString() + "\n" + richTextBox3.Text + "\n";;
                                });
                            }
                        }
                    }


                    g.Dispose();

                    //     this.Invoke((MethodInvoker)delegate
                    //{
                    //    richTextBox1.Text = objectRect.Location.ToString() + "\n" + richTextBox1.Text + "\n"; ;
                    //});
                }
            }



            if (radio_geometric.Checked)
            {
                SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

                Graphics g         = pictureBox1.CreateGraphics();
                Pen      yellowPen = new Pen(Color.Yellow, 2); // circles
                Pen      redPen    = new Pen(Color.Red, 2);    // quadrilateral
                Pen      brownPen  = new Pen(Color.Brown, 2);  // quadrilateral with known sub-type
                Pen      greenPen  = new Pen(Color.Green, 2);  // known triangle
                Pen      bluePen   = new Pen(Color.Blue, 2);   // triangle

                for (int i = 0, n = blobs.Length; i < n; i++)
                {
                    List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);

                    AForge.Point center;
                    float        radius;

                    // is circle ?
                    if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                    {
                        g.DrawEllipse(yellowPen,
                                      (float)(center.X - radius), (float)(center.Y - radius),
                                      (float)(radius * 2), (float)(radius * 2));
                    }
                    else
                    {
                        List <IntPoint> corners;

                        // is triangle or quadrilateral
                        if (shapeChecker.IsConvexPolygon(edgePoints, out corners))
                        {
                            // get sub-type
                            PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners);

                            Pen pen;

                            if (subType == PolygonSubType.Unknown)
                            {
                                pen = (corners.Count == 4) ? redPen : bluePen;
                            }
                            else
                            {
                                pen = (corners.Count == 4) ? brownPen : greenPen;
                            }

                            g.DrawPolygon(pen, ToPointsArray(corners));
                        }
                    }
                }

                yellowPen.Dispose();
                redPen.Dispose();
                greenPen.Dispose();
                bluePen.Dispose();
                brownPen.Dispose();
                g.Dispose();
            }
        }
        // Process image
        void ProcessImage(Bitmap bitmap)
        {
#if !SILVERLIGHT && !UNITY_WEBPLAYER
            // lock image
            BitmapData bitmapData = bitmap.LockBits(
                new RectI(0, 0, bitmap.PixelWidth, bitmap.PixelHeight),
                ImageLockMode.ReadWrite, bitmap.PixelFormat);

            // step 1 - turn background to black
            ColorFiltering colorFilter = new ColorFiltering();

            colorFilter.Red              = new IntRange(0, 64);
            colorFilter.Green            = new IntRange(0, 64);
            colorFilter.Blue             = new IntRange(0, 64);
            colorFilter.FillOutsideRange = false;

            colorFilter.ApplyInPlace(bitmapData);

            // step 2 - locating objects
            BlobCounter blobCounter = new BlobCounter();

            blobCounter.FilterBlobs = true;
            blobCounter.MinHeight   = 5;
            blobCounter.MinWidth    = 5;

            blobCounter.ProcessImage(bitmapData);
            Blob[] blobs = blobCounter.GetObjectsInformation();
            bitmap.UnlockBits(bitmapData);

            // step 3 - check objects' type and highlight
            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

            Graphics g         = Graphics.FromImage(bitmap);
            Pen      yellowPen = new Pen(Color.Yellow, 2); // circles
            Pen      redPen    = new Pen(Color.Red, 2);    // quadrilateral
            Pen      brownPen  = new Pen(Color.Brown, 2);  // quadrilateral with known sub-type
            Pen      greenPen  = new Pen(Color.Green, 2);  // known triangle
            Pen      bluePen   = new Pen(Color.Blue, 2);   // triangle

            for (int i = 0, n = blobs.Length; i < n; i++)
            {
                List <IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);

                global::AForge.Point center;
                float radius;

                // is circle ?
                if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                {
                    g.DrawEllipse(yellowPen,
                                  (float)(center.X - radius), (float)(center.Y - radius),
                                  (float)(radius * 2), (float)(radius * 2));
                }
                else
                {
                    List <IntPoint> corners;

                    // is triangle or quadrilateral
                    if (shapeChecker.IsConvexPolygon(edgePoints, out corners))
                    {
                        // get sub-type
                        PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners);

                        Pen pen;

                        if (subType == PolygonSubType.Unknown)
                        {
                            pen = (corners.Count == 4) ? redPen : bluePen;
                        }
                        else
                        {
                            pen = (corners.Count == 4) ? brownPen : greenPen;
                        }

                        g.DrawPolygon(pen, ToPointsArray(corners));
                    }
                }
            }

            yellowPen.Dispose();
            redPen.Dispose();
            greenPen.Dispose();
            bluePen.Dispose();
            brownPen.Dispose();
            g.Dispose();
#endif

            // and to picture box
            pictureBox.Image = bitmap;
        }