Exemple #1
0
        public void IsTriangleTest( )
        {
            Assert.AreEqual(true, shapeChecker.IsTriangle(triangle1));
            Assert.AreEqual(true, shapeChecker.IsTriangle(equilateralTriangle));
            Assert.AreEqual(true, shapeChecker.IsTriangle(isoscelesTriangle));
            Assert.AreEqual(true, shapeChecker.IsTriangle(rectangledTriangle));

            Assert.AreEqual(false, shapeChecker.IsTriangle(idealCicle));
            Assert.AreEqual(false, shapeChecker.IsTriangle(distorredCircle));

            Assert.AreEqual(false, shapeChecker.IsTriangle(square1));
            Assert.AreEqual(false, shapeChecker.IsTriangle(square2));
            Assert.AreEqual(false, shapeChecker.IsTriangle(square3));
            Assert.AreEqual(false, shapeChecker.IsTriangle(rectangle));
        }
        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]++;
            }
        }
Exemple #3
0
        static void Main(string[] args)
        {
            try
            {
                bool parm_error = false;
                if (args.Length == 0)
                {
                    exitWithHelp();                   // Exit! No param
                }
                //set mandatory parm
                string in_path = "";

                //optional parm
                bool cropcenter = false;
                bool emulate    = false;
                bool debug      = false;

                //optional blob parm
                bool   blob           = false;
                string bfilterw       = "";
                double bfilterw_min   = 1;
                double bfilterw_max   = 1;
                string bfilterh       = "";
                double bfilterh_min   = 1;
                double bfilterh_max   = 1;
                bool   blob_noff      = false;
                bool   blob_noshape   = false;
                bool   blob_notrotate = false;
                string blob_zone      = "";
                double blob_zonex     = 0.5;
                double blob_zoney     = 0.5;

                //parsing parm
                for (int p = 0; p < args.Length; p++)
                {
                    //for each parm get type and value
                    //ex. -parm value -parm2 value2
                    //get parm
                    switch (args[p])
                    {
                    case "-debug":
                        debug = true;
                        break;

                    case "-f":
                        in_path = args[p + 1];
                        break;

                    case "-cropcenter":
                        cropcenter = true;
                        break;

                    case "-emulate":
                        emulate = true;
                        break;

                    case "-blob":
                        blob = true;
                        break;

                    case "-bfilterw":
                        bfilterw = args[p + 1];
                        break;

                    case "-bfilterh":
                        bfilterh = args[p + 1];
                        break;

                    case "-bnoff":
                        blob_noff = true;
                        break;

                    case "-bzone":
                        blob_zone = args[p + 1];
                        break;

                    case "-bnoshape":
                        blob_noshape = true;
                        break;

                    case "-bnotrotate":
                        blob_notrotate = true;
                        break;

                    default:
                        if (args[p].StartsWith("-"))
                        {
                            exitNotValid(args[p]);        // Exit! Invalid param
                        }
                        break;
                    }
                }

                //check mandatory param
                if (in_path.Equals(""))
                {
                    exitWithHelp();
                }

                //check others param
                if (!bfilterw.Equals(""))
                {
                    RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline;
                    Regex        pattern = new Regex(@"((?:[0]\.)?\d+)\-((?:[0]\.)?\d+)", options);
                    Match        match   = pattern.Match(bfilterw);
                    if (match.Success && match.Groups.Count.Equals(3))
                    {
                        bfilterw_min = Convert.ToDouble(match.Groups[1].Value.Replace('.', ','));
                        bfilterw_max = Convert.ToDouble(match.Groups[2].Value.Replace('.', ','));
                    }
                    else
                    {
                        exitWithError("Opzione '-bfilterw' non valida.", "Specificare i valori minimi e massimi nel seguente formato:", "   -bfilterw valoremin-valoremax", "   es. -bfilterw 0.30-0.40");
                    }
                }
                if (!bfilterh.Equals(""))
                {
                    RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline;
                    Regex        pattern = new Regex(@"((?:[0]\.)?\d+)\-((?:[0]\.)?\d+)", options);
                    Match        match   = pattern.Match(bfilterh);
                    if (match.Success && match.Groups.Count.Equals(3))
                    {
                        bfilterh_min = Convert.ToDouble(match.Groups[1].Value.Replace('.', ','));
                        bfilterh_max = Convert.ToDouble(match.Groups[2].Value.Replace('.', ','));
                    }
                    else
                    {
                        exitWithError("Opzione '-bfilterh' non valida.", "Specificare i valori minimi e massimi nel seguente formato:", "   -bfilterh valoremin-valoremax", "   es. -bfilterh 0.30-0.40");
                    }
                }
                if (!blob_zone.Equals(""))
                {
                    RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline;
                    Regex        pattern = new Regex(@"((?:[0]\.)?\d+)\,((?:[0]\.)?\d+)", options);
                    Match        match   = pattern.Match(blob_zone);
                    if (match.Success && match.Groups.Count.Equals(3))
                    {
                        blob_zonex = Convert.ToDouble(match.Groups[1].Value.Replace('.', ','));
                        blob_zoney = Convert.ToDouble(match.Groups[2].Value.Replace('.', ','));
                    }
                    else
                    {
                        exitWithError("Opzione '-bzone' non valida.", "Specificare le coordinate del punto dove cercare il barcode.", "   -bzone x,y", "   es. -bzone 0.5,0.5");
                    }
                }

                //check validity
                if (File.Exists(in_path))
                {
                    in_path = Path.GetFullPath(in_path);
                }
                else
                {
                    exitFileNotFound(in_path);
                }

                //START
                Stopwatch stopWatch = new Stopwatch();
                if (emulate)
                {
                    stopWatch.Start();
                }

                //Convert to image if PDF
                string tmp_path = "";
                bool   tmp_file = false;
                if (Path.GetExtension(in_path).Equals(".pdf"))
                {
                    if (debug)
                    {
                        Console.WriteLine("Converting pdf...");
                    }
                    tmp_path = in_path + ".png";
                    tmp_file = true;
                    libImage.ConvertSingleImage(in_path, tmp_path, 300);
                }
                else
                {
                    tmp_path = in_path;
                }

                //Load image in memory and del file
                System.Drawing.Bitmap tmp_img;
                using (System.Drawing.Bitmap img_source = (Bitmap)Bitmap.FromFile(tmp_path))
                {
                    tmp_img = new Bitmap(img_source);
                }
                if (tmp_file)
                {
                    File.Delete(tmp_path);
                }

                //Get Info on page
                int page_w = tmp_img.Width;
                int page_h = tmp_img.Height;
                if (debug)
                {
                    Console.WriteLine("File dimension: w=" + page_w + " h=" + page_h);
                }

                //Crop Center
                if (cropcenter)
                {
                    if (debug)
                    {
                        Console.WriteLine("Cropping central image...");
                    }
                    int crop_x      = Convert.ToInt32(((double)tmp_img.Width * 0.3)),
                        crop_y      = Convert.ToInt32(((double)tmp_img.Height * 0.3)),
                        crop_width  = Convert.ToInt32(((double)tmp_img.Width * 0.7) - crop_x),
                        crop_height = Convert.ToInt32(((double)tmp_img.Height * 0.7) - crop_y);
                    //source = source.crop(crop_x, crop_y, crop_width, crop_height);
                    tmp_img = tmp_img.Clone(new Rectangle(crop_x, crop_y, crop_width, crop_height), PixelFormat.Format32bppArgb);
                    page_w  = tmp_img.Width;
                    page_h  = tmp_img.Height;
                    if (debug)
                    {
                        Console.WriteLine("New file dimension: w=" + page_w + " h=" + page_h);
                    }
                }
                else
                {
                    tmp_img = AForge.Imaging.Image.Clone(tmp_img, PixelFormat.Format32bppArgb);
                }

                //Blob Analysis
                if (blob)
                {
                    if (debug)
                    {
                        Console.WriteLine("Starting Blob Analysis...");
                    }

                    // filter GreyScale
                    Grayscale filterg = new Grayscale(0.2125, 0.7154, 0.0721);
                    tmp_img = filterg.Apply(tmp_img);
                    Bitmap tmp_img_wrk = (Bitmap)tmp_img.Clone();

                    // filter Erosion3x3
                    BinaryErosion3x3 filter = new BinaryErosion3x3();
                    tmp_img_wrk = filter.Apply(tmp_img_wrk);
                    tmp_img_wrk = filter.Apply(tmp_img_wrk);
                    tmp_img_wrk = filter.Apply(tmp_img_wrk);
                    tmp_img_wrk = filter.Apply(tmp_img_wrk);
                    tmp_img_wrk = filter.Apply(tmp_img_wrk);
                    tmp_img_wrk = filter.Apply(tmp_img_wrk);

                    //Binarization
                    SISThreshold filterSIS = new SISThreshold();
                    tmp_img_wrk = filterSIS.Apply(tmp_img_wrk);

                    //Inversion
                    Invert filterI = new Invert();
                    tmp_img_wrk = filterI.Apply(tmp_img_wrk);

                    //Blob Analisys
                    BlobCounterBase bc = new BlobCounter();
                    bc.FilterBlobs = true;
                    if (!bfilterw.Equals(""))
                    {
                        bc.MinWidth = Convert.ToInt32(page_w * bfilterw_min);   // 0.15 in proporzione è il 20%
                        bc.MaxWidth = Convert.ToInt32(page_w * bfilterw_max);   // 0.30
                    }
                    if (!bfilterh.Equals(""))
                    {
                        bc.MinHeight = Convert.ToInt32(page_h * bfilterh_min);  // 0.10 in proporzione è il 15%
                        bc.MaxHeight = Convert.ToInt32(page_h * bfilterh_max);  // 0.20
                    }
                    if (debug)
                    {
                        Console.WriteLine("Searching blob (Dimension filter: w=" + bc.MinWidth + "-" + (bc.MaxWidth.Equals(int.MaxValue) ? "max" : bc.MaxWidth.ToString()) + " h=" + bc.MinHeight + "-" + (bc.MaxHeight.Equals(int.MaxValue) ? "max": bc.MaxHeight.ToString()) + ")");
                    }
                    bc.ObjectsOrder = ObjectsOrder.Size;
                    bc.ProcessImage(tmp_img_wrk);
                    Blob[] blobs = bc.GetObjectsInformation();
                    if (debug)
                    {
                        Console.WriteLine("Blobs found: " + blobs.Count());
                    }

                    //Esamina Blobs
                    int i = 1;
                    foreach (Blob b in blobs)
                    {
                        //Escludi blob contenitore (l'immagine stessa)
                        if (b.Rectangle.Width == page_w)
                        {
                            if (debug)
                            {
                                Console.WriteLine("Blob " + i + ": skip! (is container)");
                            }
                            i++; continue;
                        }

                        //check form factor
                        if (!blob_noff)
                        {
                            double formf = (Convert.ToDouble(b.Rectangle.Width) / Convert.ToDouble(b.Rectangle.Height)) * 100;
                            if (formf < 95)
                            {
                                //skip Form Factor Not a square
                                if (debug)
                                {
                                    Console.WriteLine("Blob " + i + ": Check 1 - Form factor > 95 Failed! (form factor is not square " + formf + "<95) Blob Skipped!");
                                    Console.WriteLine("You can disable this check with -bnoff parameter.");
                                }
                                i++;  continue;
                            }
                            if (debug)
                            {
                                Console.WriteLine("Blob " + i + ": Check 1 - Form factor > 95  " + formf + " Ok!");
                            }
                        }
                        else if (debug)
                        {
                            Console.WriteLine("Blob " + i + ": Check 1 - Form factor > 95 skipped by option -bnoff ");
                        }

                        //check zone
                        if (!blob_zone.Equals(""))
                        {
                            Rectangle bZone = b.Rectangle;
                            bZone.Inflate(Convert.ToInt32(b.Rectangle.Width * 0.2), Convert.ToInt32(b.Rectangle.Height * 0.2));
                            if (!bZone.Contains(Convert.ToInt32(page_w * blob_zonex), Convert.ToInt32(page_h * blob_zoney)))
                            {
                                //skip Zone Not in center
                                if (debug)
                                {
                                    Console.WriteLine("Blob " + i + ": Check 2 - Zone of blob Failed! (Not in the zone requested! blob zone:" + b.Rectangle.ToString() + " and requested point is at x=" + Convert.ToInt32(page_w * blob_zonex) + ",y=" + Convert.ToInt32(page_h * blob_zonex) + " ) Blob Skipped!");
                                }
                                i++; continue;
                            }
                            if (debug)
                            {
                                Console.WriteLine("Blob " + i + ": Check 2 - Zone of blob contains " + Convert.ToInt32(page_w * blob_zonex) + "," + Convert.ToInt32(page_h * blob_zonex) + "...   Ok!");
                            }
                        }

                        //check shape
                        List <IntPoint>    edgePoints = bc.GetBlobsEdgePoints(b);
                        List <IntPoint>    corners;
                        SimpleShapeChecker shapeChecker = new SimpleShapeChecker();
                        if (shapeChecker.IsQuadrilateral(edgePoints, out corners))
                        {
                            if (!blob_noshape)
                            {
                                PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners);
                                if (!subType.Equals(PolygonSubType.Square))
                                {
                                    //skip Not a square
                                    if (debug)
                                    {
                                        Console.WriteLine("Blob " + i + ": Check 3 - Shape is Square Failed! (Shape is not Square! " + subType.ToString() + " detected!) Blob Skipped!");
                                        Console.WriteLine("You can disable this check with -bnoshape parameter.");
                                    }
                                    i++; continue;
                                }
                                else if (debug)
                                {
                                    Console.WriteLine("Blob " + i + ": Check 3 - Shape is Square   Ok!");
                                }
                            }
                            else if (debug)
                            {
                                Console.WriteLine("Blob " + i + ":  Check 3 - Shape is Square skipped by option -bnoshape ");
                            }
                        }
                        else
                        {
                            shapeChecker.ToString();
                            //skip Not a quadrilateral
                            if (debug)
                            {
                                Console.WriteLine("Blob " + i + ": Check 3 - Shape is Square...   Failed! (not a Quadrilateral! ConvexPolygon:" + shapeChecker.IsConvexPolygon(edgePoints, out corners) + " Triangle:" + shapeChecker.IsTriangle(edgePoints, out corners) + ") Blob Skipped!");
                            }
                            i++; continue;
                        }

                        //if (debug){ Console.WriteLine("Blob " + i + ": Trying to decode..."); }

                        //Calculate rotation angle 0 bottom left , 1 top left , 2 top right, 3 bottom right
                        double dx  = corners[2].X - corners[1].X;
                        double dy  = corners[1].Y - corners[2].Y;
                        double ang = Math.Atan2(dx, dy) * (180 / Math.PI);
                        if (ang > 90)
                        {
                            ang = ang - 90;
                        }
                        else
                        {
                            ang = 90 - ang;
                        }

                        //Extract Blob
                        Rectangle cropRect = b.Rectangle;
                        cropRect.Inflate(Convert.ToInt32(b.Rectangle.Width * 0.1), Convert.ToInt32(b.Rectangle.Height * 0.1));
                        Crop   filter_blob  = new Crop(cropRect);
                        Bitmap tmp_img_blob = filter_blob.Apply(tmp_img);

                        //Rotate
                        if (!blob_notrotate)
                        {
                            RotateBilinear filterRotate = new RotateBilinear(ang, true);
                            tmp_img_blob = filterRotate.Apply(tmp_img_blob);
                            //Togli margine esterno (bande nere derivanti dalla rotazione)
                            Rectangle cropRectInterno = new Rectangle(0, 0, tmp_img_blob.Width, tmp_img_blob.Height);
                            cropRectInterno.Inflate(-Convert.ToInt32(b.Rectangle.Width * 0.05), -Convert.ToInt32(b.Rectangle.Height * 0.05));
                            Crop filterCropInterno = new Crop(cropRectInterno);
                            tmp_img_blob = filterCropInterno.Apply(tmp_img_blob);
                            if (debug)
                            {
                                Console.WriteLine("Blob " + i + ": Rotated and aligned! (angle:" + ang + ")");
                            }
                        }
                        else
                        {
                            if (debug)
                            {
                                Console.WriteLine("Blob " + i + ": Rotation skipped by option -bnotrotate (angle:" + ang + ")");
                            }
                        }

                        //Applica filtri
                        var filter1 = new Median();
                        filter1.ApplyInPlace(tmp_img_blob);
                        var filter2 = new OtsuThreshold();
                        filter2.ApplyInPlace(tmp_img_blob);

                        //Decodifica
                        if (debug)
                        {
                            Console.WriteLine("Blob " + i + ": Extracted! Trying to decode...");
                        }
                        BarcodeReader reader = new BarcodeReader {
                            AutoRotate = true
                        };
                        Result result = reader.Decode(tmp_img_blob);

                        //Output Results
                        if (result != null)
                        {
                            if (emulate)
                            {
                                stopWatch.Stop(); Console.WriteLine("Success in " + stopWatch.Elapsed);
                            }
                            else
                            {
                                Console.WriteLine(result.Text);
                            }
                            Environment.Exit(0);
                        }
                        else if (debug)
                        {
                            Console.WriteLine("Blob " + i + ": Decode failed! (Result null)");
                        }
                    }
                }
                else
                {
                    BarcodeReader reader = new BarcodeReader {
                        AutoRotate = true
                    };
                    Result result = reader.Decode(tmp_img);

                    //Output Results
                    if (result != null)
                    {
                        if (emulate)
                        {
                            stopWatch.Stop(); Console.WriteLine(stopWatch.Elapsed);
                        }
                        else
                        {
                            Console.WriteLine(result.Text); Environment.Exit(0);
                        }
                    }
                    else if (debug)
                    {
                        Console.WriteLine("Decode failed! (Result null)");
                    }
                }

                //Exit
                if (emulate && stopWatch.IsRunning)
                {
                    stopWatch.Stop(); Console.WriteLine("Failure in " + stopWatch.Elapsed);
                }
                Environment.Exit(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Fatal Error: " + ex.Message + "\n" + ex.InnerException);
            }
        }
Exemple #4
0
        private void ParseImage(int imageId)
        {
            DateTime startTime = DateTime.Now;

            labelDetection.Text = "";

            string difImagePath = "";

            if (imageId >= 0)
            {
                difImagePath = DifBoardImages[imageId];
            }

            Bitmap orig;
            Bitmap dif;

            try
            {
                orig = (Bitmap)Bitmap.FromFile(OriginalBoardImage);

                if (imageId >= 0)
                {
                    dif = (Bitmap)Bitmap.FromFile(difImagePath);
                }
                else
                {
                    dif = (Bitmap)pictureBoxGenerated.Image;
                }
            }
            catch {
                // kill any exception due to missing files
                return;
            }

            pictureBoxOrig.Image = dif;

            Difference filter = new Difference(orig);

            dif = filter.Apply(dif);

            BlobCounter blobCounter = new BlobCounter();

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

            // create Graphics object to draw on the image and a pen
            Graphics           g            = Graphics.FromImage(dif);
            Pen                redPen       = new Pen(Color.Red, 3);
            Pen                bluePen      = new Pen(Color.Blue, 1);
            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

            // 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]);

                labelDetection.Text = string.Format("{0} points", edgePoints.Count);

                if (edgePoints.Count <= 1)
                {
                    continue;
                }

                List <IntPoint> points = new List <IntPoint>();

                if (shapeChecker.IsQuadrilateral(edgePoints))
                {
                    labelDetection.Text += ", quadrilateral";
                }
                else if (shapeChecker.IsConvexPolygon(edgePoints, out points))
                {
                    labelDetection.Text += ", convex poligon";
                }
                else if (shapeChecker.IsTriangle(edgePoints, out points))
                {
                    labelDetection.Text += ", triangle";
                }

                Pen usePen = shapeChecker.IsQuadrilateral(edgePoints) ? redPen : bluePen;

                int centerX = edgePoints[0].X;
                int centerY = edgePoints[0].Y;
                int minX    = centerX;
                int minY    = centerY;
                int maxX    = centerX;
                int maxY    = centerY;
                for (int j = 0; j < edgePoints.Count - 1; j++)
                {
                    centerX += edgePoints[j + 1].X;
                    centerY += edgePoints[j + 1].Y;

                    if (edgePoints[j + 1].X < minX)
                    {
                        minX = edgePoints[j + 1].X;
                    }
                    if (edgePoints[j + 1].Y < minY)
                    {
                        minY = edgePoints[j + 1].Y;
                    }
                    if (edgePoints[j + 1].X > maxX)
                    {
                        maxX = edgePoints[j + 1].X;
                    }
                    if (edgePoints[j + 1].Y > maxX)
                    {
                        maxX = edgePoints[j + 1].Y;
                    }

                    g.DrawLine(usePen, edgePoints[j].X, edgePoints[j].Y, edgePoints[j + 1].X, edgePoints[j + 1].Y);
                }

                g.DrawLine(usePen
                           , edgePoints[0].X, edgePoints[0].Y
                           , edgePoints[edgePoints.Count - 1].X, edgePoints[edgePoints.Count - 1].Y);

                labelDetectedPosition.Text = string.Format("{0}, {1}"
                                                           , new object[] {
                    (centerX / edgePoints.Count), (centerY / edgePoints.Count)
                    //, maxX - minX, maxY - minY
                });
                labelDetectionOffset.Text = string.Format("{0}, {1}"
                                                          , Grigore.Position.X - (centerX / edgePoints.Count)
                                                          , Grigore.Position.Y - (centerY / edgePoints.Count)
                                                          );
            }

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

            pictureBoxRoboBoard.Image = dif;

            labelDetection.Text = string.Format("{1}, {0} sec", (DateTime.Now - startTime), labelDetection.Text);
        }
Exemple #5
0
        //Blob Detection
        private Bitmap BlobDetection(Bitmap _bitmapSourceImage)
        {
            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;
            }

            Grayscale _grayscale = new Grayscale(0.2125, 0.7154, 0.0721);

            _bitmapGreyImage = _grayscale.Apply(_colorFilterImage);

            //create a edge detector instance
            if (_blurFlag == true)
            {
                //Blur _blurfilter = new Blur();
                GaussianBlur _blurfilter = new GaussianBlur();
                _bitmapBlurImage = _blurfilter.Apply(_bitmapGreyImage);
                _bitmapEdgeImage = _edgeFilter.Apply(_bitmapBlurImage);
            }
            else if (_blurFlag == false)
            {
                _bitmapEdgeImage = _edgeFilter.Apply(_bitmapGreyImage);
            }

            Threshold _threshold = new Threshold(iThreshold);

            _bitmapBinaryImage = _threshold.Apply(_bitmapEdgeImage);

            //Create a instance of blob counter algorithm
            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;

                if (_shapeChecker.IsQuadrilateral(_edgePoint, out _corners))
                {
                    Rectangle[] _rects = _blobCounter.GetObjectsRectangles();

                    System.Drawing.Point[] _coordinates = ToPointsArray(_corners);
                    int _x   = _coordinates[0].X;
                    int _y   = _coordinates[0].Y;
                    Pen _pen = new Pen(Color.Blue, ipenWidth);

                    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;
                        double dis = FindDistance(iFeatureWidth);
                        _g.DrawString(dis.ToString("N2"), _font, _brush, _x, _y + 60);
                    }
                }
                if (_shapeChecker.IsCircle(_edgePoint, out _center, out _radius))
                {
                    Rectangle[] _rects = _blobCounter.GetObjectsRectangles();

                    string _shapeString = "" + _shapeChecker.CheckShapeType(_edgePoint);
                    Pen    _pen         = new Pen(Color.Red, ipenWidth);
                    int    _x           = (int)_center.X;
                    int    _y           = (int)_center.Y;
                    _g.DrawString(_shapeString, _font, _brush, _x, _y);
                    _g.DrawEllipse(_pen, (float)(_center.X - _radius),
                                   (float)(_center.Y - _radius),
                                   (float)(_radius * 2),
                                   (float)(_radius * 2));

                    //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);
                        //textBox1.Text = dis.ToString("N2");
                        _g.DrawString(dis.ToString("N2"), _font, _brush, _x, _y + 60);
                    }
                }
                if (_shapeChecker.IsTriangle(_edgePoint, out _corners))
                {
                    Rectangle[] _rects = _blobCounter.GetObjectsRectangles();

                    string _shapeString = "" + _shapeChecker.CheckShapeType(_edgePoint);
                    Pen    _pen         = new Pen(Color.Green, ipenWidth);
                    int    _x           = (int)_center.X;
                    int    _y           = (int)_center.Y;
                    _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("Triangle Size: ({0}, {1})", rc.Width, rc.Height));

                        iFeatureWidth = rc.Width;
                        double dis = FindDistance(iFeatureWidth);
                        //textBox1.Text = dis.ToString("N2");
                        _g.DrawString(dis.ToString("N2"), _font, _brush, _x, _y + 60);
                    }
                }
            }
            return(_bitmapSourceImage);
        }
        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)
                    {
                        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;
                    textBox1.Text = ("Degree: (" + _deg_x + ", " + _deg_y + ")");

                    //size of rectange
                    foreach (Rectangle rc in _rects)
                    {
                        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)
                    {
                        iFeatureWidth = rc.Width;
                        double dis = FindDistance(iFeatureWidth);
                        _g.DrawString(dis.ToString("N2") + "cm", _font, _brush, _x, _y + 60);
                    }
                }
                #endregion
            }
            return(_bitmapSourceImage);
        }
Exemple #7
0
        private void ParseImage(int imageId)
        {
            DateTime startTime = DateTime.Now;

            Console.WriteLine(string.Format("Start parsing {0}", startTime));

            string difImagePath = "";

            if (imageId >= 0)
            {
                difImagePath = DifBoardImages[imageId];
            }

            Bitmap orig;
            Bitmap dif;

            try
            {
                Console.WriteLine("Load files");

                orig = (Bitmap)Bitmap.FromFile(OriginalBoardImage);

                if (imageId >= 0)
                {
                    dif = (Bitmap)Bitmap.FromFile(difImagePath);
                }
                else
                {
                    dif = (Bitmap)internalImageContainer;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERR: " + ex.Message);
                Console.WriteLine(ex.StackTrace);

                // kill any exception due to missing files
                return;
            }

            Difference filter = new Difference(orig);

            dif = filter.Apply(dif);
            Console.WriteLine("Apply difference filter");

            BlobCounter blobCounter = new BlobCounter();

            blobCounter.ProcessImage(dif);
            Console.WriteLine("Blob counting");
            Blob[] blobs = blobCounter.GetObjectsInformation();

            // create Graphics object to draw on the image and a pen
            Graphics           g            = Graphics.FromImage(dif);
            Pen                redPen       = new Pen(Color.Red, 3);
            Pen                bluePen      = new Pen(Color.Blue, 1);
            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

            // 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]);

                Console.Write(string.Format("Detected {0} points", edgePoints.Count));

                if (edgePoints.Count <= 1)
                {
                    continue;
                }

                List <IntPoint> points = new List <IntPoint>();

                if (shapeChecker.IsQuadrilateral(edgePoints))
                {
                    Console.Write(", quadrilateral");
                }
                else if (shapeChecker.IsConvexPolygon(edgePoints, out points))
                {
                    Console.Write(", convex poligon");
                }
                else if (shapeChecker.IsTriangle(edgePoints, out points))
                {
                    Console.Write(", triangle");
                }

                Pen usePen = shapeChecker.IsQuadrilateral(edgePoints) ? redPen : bluePen;

                int centerX = edgePoints[0].X;
                int centerY = edgePoints[0].Y;

                for (int j = 0; j < edgePoints.Count - 1; j++)
                {
                    centerX += edgePoints[j + 1].X;
                    centerY += edgePoints[j + 1].Y;

                    g.DrawLine(usePen, edgePoints[j].X, edgePoints[j].Y, edgePoints[j + 1].X, edgePoints[j + 1].Y);
                }

                // add last point
                centerX += edgePoints[edgePoints.Count - 1].X;
                centerY += edgePoints[edgePoints.Count - 1].Y;

                g.DrawLine(usePen
                           , edgePoints[0].X, edgePoints[0].Y
                           , edgePoints[edgePoints.Count - 1].X, edgePoints[edgePoints.Count - 1].Y);

                Console.WriteLine(string.Format("\nOriginal (x, y): {0}, {1}"
                                                , new object[] {
                    (centerX / edgePoints.Count), (centerY / edgePoints.Count)
                }));
                Console.WriteLine(string.Format("Detected (x, y): {0}, {1}"
                                                , (centerX / edgePoints.Count)
                                                , (centerY / edgePoints.Count)
                                                ));
            }

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

            //DifI = dif;
            dif.Save(dirPath + "processed-dif.jpg");

            Console.WriteLine(string.Format("Duration: {0} sec", (DateTime.Now - startTime)));
        }
Exemple #8
0
        private Bitmap BlobDetection(Bitmap bitmap)
        {
            var clone            = bitmap.Clone() as Bitmap;
            var grayscaledBitmap = Grayscale.CommonAlgorithms.BT709.Apply(clone);

            new Threshold(Threshold).ApplyInPlace(grayscaledBitmap);

            BlobCounter blobCounter = new BlobCounter();

            blobCounter.FilterBlobs  = true;
            blobCounter.MinWidth     = 70;
            blobCounter.MinHeight    = 70;
            blobCounter.ObjectsOrder = ObjectsOrder.Size;
            blobCounter.ProcessImage(grayscaledBitmap);

            Blob[]   blobs = blobCounter.GetObjectsInformation();
            Bitmap   tmp   = new Bitmap(grayscaledBitmap.Width, grayscaledBitmap.Height);
            Graphics g     = Graphics.FromImage(tmp);

            g.DrawImage(grayscaledBitmap, new Rectangle(0, 0, tmp.Width, tmp.Height), 0, 0, tmp.Width, tmp.Height, GraphicsUnit.Pixel);
            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

            List <IntPoint> edgePoints;
            List <IntPoint> c = null;
            float           radius;

            AForge.Point center;

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

                if (shapeChecker.IsQuadrilateral(edgePoints, out c))
                {
                    System.Drawing.Point[] coordinates = ToPointsArray(c);
                    Pen p = new Pen(Color.Blue, ipenWidth);

                    if (coordinates.Length == 4)
                    {
                        if (ShapeDetection)
                        {
                            Rectangle += 1;
                            rTmp       = Rectangle;
                        }

                        PaintPolygon(c, bitmap, p);
                    }
                }

                if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                {
                    Pen p = new Pen(Color.Red, ipenWidth);

                    if (ShapeDetection)
                    {
                        Circle += 1;
                        cTmp    = Circle;
                    }

                    PaintEllipse(bitmap, p, (float)(center.X - radius), (float)(center.Y - radius), (float)(radius * 2), (float)(radius * 2));
                }

                if (shapeChecker.IsTriangle(edgePoints, out c))
                {
                    System.Drawing.Point[] coordinates = ToPointsArray(c);
                    Pen p = new Pen(Color.Green, ipenWidth);

                    if (coordinates.Length == 3)
                    {
                        if (ShapeDetection)
                        {
                            Triangle += 1;
                            tTmp      = Triangle;
                        }

                        PaintPolygon(c, bitmap, p);
                    }
                }
            }

            if (Renewal)
            {
                Circle = 0; Rectangle = 0; Triangle = 0;
                clickX = 0; clickY = 0; clickZ = 0;

                for (int j = 0, k = blobs.Length; j < k; j++)
                {
                    edgePoints = blobCounter.GetBlobsEdgePoints(blobs[j]);

                    if (shapeChecker.IsQuadrilateral(edgePoints, out c))
                    {
                        System.Drawing.Point[] coordinates = ToPointsArray(c);
                        if (coordinates.Length == 4)
                        {
                            Rectangle += 1;
                        }
                    }

                    if (shapeChecker.IsTriangle(edgePoints, out c))
                    {
                        System.Drawing.Point[] coordinates = ToPointsArray(c);
                        if (coordinates.Length == 3)
                        {
                            Triangle += 1;
                        }
                    }

                    if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                    {
                        Circle += 1;
                    }
                }
            }

            Renewal        = false;
            ShapeDetection = false;

            return(bitmap);
        }