Blob counter - counts objects in image, which are separated by black background.

The class counts and extracts stand alone objects in images using connected components labeling algorithm.

The algorithm treats all pixels with values less or equal to BackgroundThreshold as background, but pixels with higher values are treated as objects' pixels.

For blobs' searching the class supports 8 bpp indexed grayscale images and 24/32 bpp color images that are at least two pixels wide. Images that are one pixel wide can be processed if they are rotated first, or they can be processed with RecursiveBlobCounter. See documentation about BlobCounterBase for information about which pixel formats are supported for extraction of blobs.

Sample usage:

// create an instance of blob counter algorithm BlobCounter bc = new BlobCounter( ); // process binary image bc.ProcessImage( image ); Rectangle[] rects = bc.GetObjectsRectangles( ); // process blobs foreach ( Rectangle rect in rects ) { // ... }
Inheritance: BlobCounterBase
示例#1
0
        /// <summary>
        /// Applies the blob extraction feature of Aforge
        /// </summary>
        /// <param name="Mask">Mask from the flood-fill step</param>
        /// <param name="Source">Source image (full image)</param>
        /// <returns>A list of tuples(blob from mask, rectangle from source)</returns>
        private static List <Tuple <Bitmap, Bitmap> > ApplyBlobExtractor(Bitmap Mask, Bitmap Source)
        {
            List <Tuple <Bitmap, Bitmap> > BlobSrcblock = new List <Tuple <Bitmap, Bitmap> >();

            log.Debug("Using AForge Blob Counter to Process Mask");
            AForge.Imaging.BlobCounter blobCounter = new AForge.Imaging.BlobCounter();

            // Sort order
            blobCounter.ObjectsOrder = AForge.Imaging.ObjectsOrder.XY;
            blobCounter.ProcessImage(Mask);
            AForge.Imaging.Blob[] blobs = blobCounter.GetObjects(Mask, false);

            log.Info("Use the Blob Extraction Results to reverse extract blobs from images");
            // Adding images into the image list
            AForge.Imaging.UnmanagedImage currentImg;
            foreach (AForge.Imaging.Blob blob in blobs)
            {
                Rectangle myRect = blob.Rectangle;
                currentImg = blob.Image;
                Bitmap exBlob = currentImg.ToManagedImage();
                AForge.Imaging.Filters.Crop filter = new AForge.Imaging.Filters.Crop(myRect);
                Bitmap exSrc = filter.Apply(Source);
                BlobSrcblock.Add(new Tuple <Bitmap, Bitmap>(exBlob, exSrc));
            }
            log.Info("Extraction Complete: returning List of ( blob bitmap, src bitmap)");
            return(BlobSrcblock);
        }
        public override void calcDescriptorInfo(Bitmap inImage)
        {
            shapeCount = new int[6];

            originalImage = image;
            image = imgProcessor.preProcessImage(inImage);

            g = Graphics.FromImage(originalImage);

            BlobCounter bCounter = new BlobCounter();
            bCounter.ProcessImage(image);
            Blob[] blobs = bCounter.GetObjectsInformation();

            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

            for (int i = 0; i < blobs.Length; i++)
            {
                if (blobs[i].Area < 100)
                {
                    continue;
                }
                List<IntPoint> edgePts = bCounter.GetBlobsEdgePoints(blobs[i]);
                checkShape(shapeChecker, edgePts);

            }

            g.Dispose();
        }
示例#3
0
        private Blob getBlobMaisAlto(String path)
        {
            try
            {
                Bitmap image = hslImage(path);

                // process image with blob counter
                BlobCounter blobCounter = new BlobCounter();
                blobCounter.ProcessImage(image);
                Blob[] blobs = blobCounter.GetObjectsInformation();

                Blob blobMaisAlto = blobs[0];

                // process each blob
                foreach (Blob blob in blobs)
                {
                    if (blob.CenterOfGravity.Y < blobMaisAlto.CenterOfGravity.Y)
                        blobMaisAlto = blob;
                }

                return blobMaisAlto;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Get rectangle contain object in current frame
        /// </summary>
        /// <param name="templateInfo">Tracking template information</param>
        /// <param name="source">Frame</param>
        /// <returns>Rectangle contain object</returns>
        public static Rectangle TemplateColorTracking(ImageStatistics templateInfo, ref UnmanagedImage source)
        {
            UnmanagedImage image = source.Clone();
            // create filter
            EuclideanColorFiltering filter = new EuclideanColorFiltering();
            // set center colol and radius
            filter.CenterColor = new RGB(
                (byte)templateInfo.Red.Mean,
                (byte)templateInfo.Green.Mean,
                (byte)templateInfo.Blue.Mean);
            filter.Radius = 30;
            // apply the filter
            filter.ApplyInPlace(image);

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

            OtsuThreshold threshold = new OtsuThreshold();
            threshold.ApplyInPlace(image);

            BlobCounter blobCounter = new BlobCounter();
            blobCounter.ObjectsOrder = ObjectsOrder.Size;
            blobCounter.ProcessImage(image);

            Rectangle rect = blobCounter.ObjectsCount > 0 ? blobCounter.GetObjectsRectangles()[0] : Rectangle.Empty;
            return rect;
        }
示例#5
0
        public static void blob_setter(Bitmap video , Bitmap grayImage , int height , int width)
        {
            BlobCounter blobCounter = new BlobCounter();
            // configure it to filter out small objects
            blobCounter.MinWidth = width;
            blobCounter.MinHeight = height;
             //       blobCounter.FilterBlobs = true;
            // set ordering - bigger objects go first
            blobCounter.ObjectsOrder = ObjectsOrder.Size;
            // locate blobs
            blobCounter.ProcessImage(grayImage);
            Rectangle[] rects = blobCounter.GetObjectsRectangles();

            foreach (Rectangle recs in rects)
                if (rects.Length > 0)
                {
                    Rectangle objectRect = rects[0];
                    Graphics g = Graphics.FromImage(video);
                    using (Pen pen = new Pen(Color.FromArgb(160, 255, 160), 3))
                    {
                        g.DrawRectangle(pen, objectRect);
                    }
                    g.Dispose();
                }
        }
示例#6
0
        private String ContainBlue(Bitmap bitmap)
        {
            HSLFiltering blueFilter = new HSLFiltering();

            blueFilter.Hue        = new IntRange(150, 210);
            blueFilter.Saturation = new Range(0.3f, 1);
            blueFilter.Luminance  = new Range(0.20f, 0.8f);
            blueFilter.ApplyInPlace(bitmap);


            AForge.Imaging.BlobCounter blobCounterBlue = new AForge.Imaging.BlobCounter();
            blobCounterBlue.FilterBlobs  = true;
            blobCounterBlue.ObjectsOrder = ObjectsOrder.Area;
            blobCounterBlue.MinHeight    = 10;
            blobCounterBlue.MinWidth     = 10;
            blobCounterBlue.ProcessImage(bitmap);
            //capturedPhotoBlue.Source = (WriteableBitmap)bitmap;
            AForge.Imaging.Blob[] blobsBlue = blobCounterBlue.GetObjectsInformation();
            for (int iBlob = 0; iBlob < blobsBlue.Length; iBlob++)
            {
                for (int jBlob = iBlob + 1; jBlob < blobsBlue.Length; jBlob++)
                {
                    if ((Math.Abs(blobsBlue[iBlob].CenterOfGravity.X - blobsBlue[jBlob].CenterOfGravity.X) < blobsBlue[iBlob].Rectangle.Width / 2) &&
                        (Math.Abs(blobsBlue[iBlob].CenterOfGravity.Y - blobsBlue[jBlob].CenterOfGravity.Y) < 3 * blobsBlue[iBlob].Rectangle.Height) &&
                        (Math.Abs(blobsBlue[iBlob].Area - blobsBlue[jBlob].Area) < blobsBlue[iBlob].Area / 2))
                    {
                        //try { text_log.Text += "i" + iBlob + "j" + jBlob + "diff" + Math.Abs(blobsBlue[iBlob].CenterOfGravity.X - blobsBlue[jBlob].CenterOfGravity.X) + "w" + blobsBlue[iBlob].Rectangle.Width / 2; }
                        //catch (Exception ex) { text_log.Text = ex + ""; }
                        return("Blue");
                    }
                }
            }

            return("");
        }
示例#7
0
        private String ContainGreen(Bitmap bitmap)
        {
            HSLFiltering filter = new HSLFiltering();

            // set color ranges to keep
            filter.Hue        = new IntRange(80, 150);
            filter.Saturation = new Range(0.4f, 1);
            filter.Luminance  = new Range(0.2f, 0.7f);
            filter.ApplyInPlace(bitmap);
            AForge.Imaging.BlobCounter blobCounterGreen = new AForge.Imaging.BlobCounter();
            blobCounterGreen.FilterBlobs  = true;
            blobCounterGreen.ObjectsOrder = ObjectsOrder.Area;
            blobCounterGreen.MinHeight    = 10;
            blobCounterGreen.MinWidth     = 10;
            blobCounterGreen.ProcessImage(bitmap);
            //capturedPhotoGreen.Source = (WriteableBitmap)bitmap;
            AForge.Imaging.Blob[] blobsGreen = blobCounterGreen.GetObjectsInformation();
            for (int iBlob = 0; iBlob < blobsGreen.Length; iBlob++)
            {
                for (int jBlob = iBlob + 1; jBlob < blobsGreen.Length; jBlob++)
                {
                    if ((Math.Abs(blobsGreen[iBlob].CenterOfGravity.X - blobsGreen[jBlob].CenterOfGravity.X) < blobsGreen[iBlob].Rectangle.Width / 2) &&
                        (Math.Abs(blobsGreen[iBlob].CenterOfGravity.Y - blobsGreen[jBlob].CenterOfGravity.Y) < 3 * blobsGreen[iBlob].Rectangle.Height) &&
                        (Math.Abs(blobsGreen[iBlob].Area - blobsGreen[jBlob].Area) < blobsGreen[iBlob].Area / 2))
                    {
                        //try { text_log.Text += "i" + iBlob + "j" + jBlob + "diff" + Math.Abs(blobsGreen[iBlob].CenterOfGravity.X - blobsGreen[jBlob].CenterOfGravity.X) + "w" + blobsGreen[iBlob].Rectangle.Width / 2; }
                        //catch (Exception ex) { text_log.Text = ex + ""; }
                        return("Green");
                    }
                }
            }
            //text_log.Text += "nG";
            return("");
        }
示例#8
0
        public void DetectShapes()
        {
            int       count                    = 40;
            int       minSize                  = 5;
            int       maxSize                  = 80;
            var       image                    = (Bitmap)Image.FromFile(@"C:\Users\marco\Downloads\PanoBeam\capture_pattern0.png");
            Rectangle clippingRectangle        = new Rectangle(new Point(563, 360), new Size(1156, 382));
            var       clippingRectangleCorners = new[]
            {
                new AForge.IntPoint(clippingRectangle.X, clippingRectangle.Y),
                new AForge.IntPoint(clippingRectangle.X + clippingRectangle.Width, clippingRectangle.Y),
                new AForge.IntPoint(clippingRectangle.X + clippingRectangle.Width, clippingRectangle.Y + clippingRectangle.Height),
                new AForge.IntPoint(clippingRectangle.X, clippingRectangle.Y + clippingRectangle.Height)
            };

            Helpers.FillOutsideBlack(image, clippingRectangleCorners);

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

            AForge.Imaging.Blob[] blobs;
            blobCounter.FilterBlobs = true;
            blobCounter.MaxHeight   = maxSize;
            blobCounter.MaxWidth    = maxSize;
            blobCounter.MinHeight   = minSize;
            blobCounter.MinWidth    = minSize;

            var threshold = Recognition.GetThreshold(image);

            blobCounter.BackgroundThreshold = Color.FromArgb(255, threshold, threshold, threshold);
            blobCounter.ProcessImage(image);
            blobs = blobCounter.GetObjectsInformation();
        }
 void FinalVideo_NewFrame(object sender, NewFrameEventArgs eventArgs)
 {
     Icon newIcon = new Icon(@"c:\users\gregster\documents\visual studio 2012\Projects\WebCamTrack\WebCamTrack\bin\Debug\favicon.ico");
     BlobCounter bc = new BlobCounter();
     EuclideanColorFiltering filter = new EuclideanColorFiltering();
     Bitmap video = (Bitmap)eventArgs.Frame.Clone();//sem filtro
     Bitmap video1 = (Bitmap)eventArgs.Frame.Clone();// imagem com filtro
     //
     filter.CenterColor = new RGB(0, 0, 0);
     filter.Radius = 100;
     filter.ApplyInPlace(video1);//aplicando o filtro
     bc.MinWidth = 5;
     bc.MinHeight = 5;
     bc.FilterBlobs = true;
     //  bc.ObjectsOrder = ObjectsOrder.Size;
     bc.ProcessImage(video1);// processando a imagem que ja foi filtrada para identificar objetos
     Rectangle[] rects = bc.GetObjectsRectangles();
     foreach (Rectangle recs in rects)
         if (rects.Length > 0)
         {
             Rectangle objectRect = rects[0];
             Graphics g = Graphics.FromImage(video);//identificar objetos a partir da imagem com filtro
             Graphics h = Graphics.FromImage(video1);
             using (Pen pen = new Pen(Color.FromArgb(160, 255, 160), 5))
             {
                 g.DrawIcon(newIcon, objectRect);
                // g.DrawRectangle(pen, objectRect);
                 h.DrawRectangle(pen, objectRect);
             }
             g.Dispose();
             h.Dispose();
         }
     pictureBox1.Image = video;
     pictureBox2.Image = video1;
 }
示例#10
0
        public override void Execute(Bitmap Image)
        {
            BlobCounter blobCounter = new BlobCounter();
            blobCounter.MinHeight = 75;
            blobCounter.MinWidth = 75;
            blobCounter.CoupledSizeFiltering = true;
            blobCounter.ProcessImage(Image);
            Blob[] blobs = blobCounter.GetObjects(Image);
            int maxSize = 0;
            Blob maxObject = new Blob(0, new Rectangle(0, 0, 0, 0));
            // find biggest blob
            if (blobs != null)
            {
                foreach (Blob blob in blobs)
                {
                    int blobSize = blob.Rectangle.Width * blob.Rectangle.Height;

                    if (blobSize > maxSize)
                    {
                        maxSize = blobSize;
                        maxObject = blob;
                    }
                }
                if (maxSize > 100)
                {
                    if (Validity == ValidLocation.TRUE)
                    {
                        if (System.Math.Sqrt((CurrY - maxObject.Rectangle.Top) * (CurrY - maxObject.Rectangle.Top) + (CurrX - (maxObject.Rectangle.Left + maxObject.Rectangle.Right) / 2) * (CurrX - (maxObject.Rectangle.Left + maxObject.Rectangle.Right) / 2)) > 20)
                        {
                            Validity = ValidLocation.FALSE;
                            TargetFoundCycle = 0;
                            return;
                        }
                        else
                        {
                            TargetFoundCycle++;
                        }
                    }
                    CurrX = (maxObject.Rectangle.Left + maxObject.Rectangle.Right) / 2;
                    CurrY = maxObject.Rectangle.Top;
                    Validity = ValidLocation.TRUE;
                }
                else
                {
                    Validity = ValidLocation.FALSE;
                    TargetFoundCycle = 0;
                }
            }
            else
            {
                TargetFoundCycle = 0;
                Validity = ValidLocation.FALSE;
                return;
            }
        }
示例#11
0
        /// <summary>
        /// Méthode qui analyse les images envoyées par le client
        /// Repère les formes présentes, les découpe et les enregistre en ficiers distincts
        /// </summary>
        public void ProcessImage()
        {
            using (CamCapturer.CamCapturer cam = new CamCapturer.CamCapturer())
            {
                Picture = cam.GetCapture();
                Copy = cam.GetCapture();
            }

            ShapeChecker = new SimpleShapeChecker();
            ShapeAnalyser = new BlobCounter();
            string date = DateTime.Now.Date.ToString("dMyyyy");
            FolderName = string.Format("Kuhlschrank-{0}", date);

            ShapeAnalyser.FilterBlobs = true;
            ShapeAnalyser.MinHeight = 200;
            ShapeAnalyser.MinWidth = 500;
            Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), FolderName));

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

            ColorFiltering filter = new ColorFiltering();

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

            filter.ApplyInPlace(bitData);

            ShapeAnalyser.ProcessImage(bitData);
            Blob[] blobs = ShapeAnalyser.GetObjectsInformation();
            Picture.UnlockBits(bitData);

            for (int i = 0; i < blobs.Length; i++)
            {
                List<IntPoint> edgePoints = ShapeAnalyser.GetBlobsEdgePoints(blobs[i]);
                List<IntPoint> corners;
                ShapeChecker.IsConvexPolygon(edgePoints, out corners);

                IntPoint pt0 = corners[0];
                IntPoint pt1 = corners[1];
                IntPoint pt2 = corners[2];

                double width = Math.Sqrt(Math.Pow(pt1.X - pt0.X, 2) + Math.Pow(pt1.Y - pt0.Y, 2));
                double height = Math.Sqrt(Math.Pow(pt2.X - pt1.X, 2) + Math.Pow(pt2.Y - pt1.Y, 2));

                Rectangle crop = new Rectangle(corners[0].X, corners[1].Y, (int)width + 50, (int)height + 50);
                Bitmap target = new Bitmap(crop.Width, crop.Height);
                using (Graphics gr = Graphics.FromImage(target))
                    gr.DrawImage(Copy, new Rectangle(0, 0, target.Width, target.Height), crop, GraphicsUnit.Pixel);

                target.Save(string.Format(@"{0}\{1}\crop{2}.jpg", Path.GetTempPath(), FolderName, i));
            }
        }
示例#12
0
        public virtual void Initialize(Bitmap backgroundImage)
        {
            fSequence = new FiltersSequence();
            BlobCounter = new BlobCounter();

            BlobCounter.MinWidth = BlobCounter.MinHeight = Global.AppSettings.MinBlobSize;
            BlobCounter.MaxWidth = BlobCounter.MaxWidth = Global.AppSettings.MaxBlobSize;
            BlobCounter.FilterBlobs = Global.AppSettings.FilterBlobs;
            BlobCounter.ObjectsOrder = ObjectsOrder.None;

            Initialized = true;
        }
        public FrameProcessor(LaserController controller)
        {
            _controller = controller;
            var min_size_val = 8;

            bc = new BlobCounter();
            bc.FilterBlobs = true;
            bc.MinHeight = min_size_val;
            bc.MinWidth = min_size_val;
            bc.MaxHeight = min_size_val + 50;
            bc.MaxWidth = min_size_val + 50;
        }
示例#14
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;
        }
示例#15
0
        private Boolean colorOfPlayer(Bitmap bitmap)
        {
            Boolean ok = false;

            HSLFiltering filterRed = new HSLFiltering();

            filterRed.Hue        = new IntRange(301, 9);   //red at night (334, 40)
            filterRed.Saturation = new Range(0.4f, 1);     //0.55
            filterRed.Luminance  = new Range(0.1f, 0.68f); //75
            filterRed.ApplyInPlace(bitmap);

            AForge.Imaging.BlobCounter blobCounterRed = new AForge.Imaging.BlobCounter();
            blobCounterRed.FilterBlobs  = true;
            blobCounterRed.ObjectsOrder = ObjectsOrder.Area;
            blobCounterRed.MinHeight    = 10;
            blobCounterRed.MinWidth     = 10;
            try { blobCounterRed.ProcessImage(bitmap); } catch (Exception es) { gameUpdate.Text = "filter"; }


            AForge.Imaging.Blob[] blobsRed = blobCounterRed.GetObjectsInformation();
            //Mean filter = new Mean();
            //// apply the filter
            //filter.ApplyInPlace(bitmap);
            bool fin = false;

            try
            {
                for (int iBlob = 0; iBlob < blobsRed.Length; iBlob++)
                {
                    for (int jBlob = iBlob + 1; jBlob < blobsRed.Length; jBlob++)
                    {
                        if ((Math.Abs(blobsRed[iBlob].CenterOfGravity.X - blobsRed[jBlob].CenterOfGravity.X) < blobsRed[iBlob].Rectangle.Width / 2) &&
                            (Math.Abs(blobsRed[iBlob].CenterOfGravity.Y - blobsRed[jBlob].CenterOfGravity.Y) < 3 * blobsRed[iBlob].Rectangle.Height) &&
                            (Math.Abs(blobsRed[iBlob].Area - blobsRed[jBlob].Area) < blobsRed[iBlob].Area / 2))
                        {
                            // gameUpdate.Text = "OK" + SharedInformation.myNumber + getPlayerNumberByColor("Red");
                            ortcExample.DoSendMessage(SharedInformation.myNumber + getPlayerNumberByColor("Red"));
                            fin = true;
                            return(true);
                        }
                    }
                    if (fin)
                    {
                        break;
                    }
                }
            }
            catch (Exception es) {
                gameUpdate.Text = "erreur";
            }
            return(ok);
        }
示例#16
0
        /// <summary>
        /// Celem metody jest przykadrowanie otrzymanego obrazka, tak aby widok zawierał jedynie kartkę papieru, oraz zwrócenie go do metody UploadFile
        /// </summary>
        /// <param name="img"></param>
        /// <returns></returns>
        public System.Drawing.Image CropImage(System.Drawing.Image img)
        {
            //DocumentSkewChecker skewChecker = new DocumentSkewChecker();
            //double angle = skewChecker.GetSkewAngle(image);
            //RotateBilinear rotationFilter = new RotateBilinear(-angle);
            //rotationFilter.FillColor = Color.White;
            //Bitmap rotatedImage = rotationFilter.Apply(image);

            Bitmap image = new Bitmap(img);

            UnmanagedImage grayImage = null;

            if (image.PixelFormat == PixelFormat.Format8bppIndexed)
            {
                grayImage = UnmanagedImage.FromManagedImage(image);
            }
            else
            {
                grayImage = UnmanagedImage.Create(image.Width, image.Height,
                    PixelFormat.Format8bppIndexed);
                Grayscale.CommonAlgorithms.BT709.Apply(UnmanagedImage.FromManagedImage(image), grayImage);
            }

            CannyEdgeDetector edgeDetector = new CannyEdgeDetector();
            UnmanagedImage edgesImage = edgeDetector.Apply(grayImage);

            OtsuThreshold thresholdFilter = new OtsuThreshold();
            thresholdFilter.ApplyInPlace(edgesImage);

            Dilatation DilatationFilter = new Dilatation();
            DilatationFilter.Apply(edgesImage);

            Opening OpeningFilter = new Opening();
            OpeningFilter.Apply(edgesImage);

            BlobCounter blobCounter = new BlobCounter();
            blobCounter.MinHeight = 32;
            blobCounter.MinWidth = 32;
            blobCounter.FilterBlobs = true;
            blobCounter.ObjectsOrder = ObjectsOrder.Size;

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

            ExtractBiggestBlob BiggestBlob = new ExtractBiggestBlob();
            Bitmap biggestBlobsImage = BiggestBlob.Apply(edgesImage.ToManagedImage());
            AForge.IntPoint BiggestBlogCorners = BiggestBlob.BlobPosition;

            Crop cropFilter = new Crop(new Rectangle(BiggestBlogCorners.X, BiggestBlogCorners.Y, biggestBlobsImage.Width, biggestBlobsImage.Height));
            Bitmap croppedImage = cropFilter.Apply(image);
            return croppedImage;
        }
        // set color ranges to keep
        public FrameProcessor(LaserController controller)
        {
            _controller = controller;
            var min_size_val = 4;

            bc = new BlobCounter();
            bc.FilterBlobs = true;
            bc.MinHeight = min_size_val;
            bc.MinWidth = min_size_val;
            bc.MaxHeight = min_size_val + 50;
            bc.MaxWidth = min_size_val + 50;

            AForge.Imaging.Filters.HSLFiltering hslFilter = new AForge.Imaging.Filters.HSLFiltering();
        }
示例#18
0
        private void colorOfPlayer2(Bitmap bitmap2)
        {
            Bitmap bit2 = null;

            bit2 = bitmap2;
            bool         fin    = false;
            HSLFiltering filter = new HSLFiltering();

            // set color ranges to keep
            filter.Hue        = new IntRange(150, 210);
            filter.Saturation = new Range(0.3f, 1);
            filter.Luminance  = new Range(0.20f, 0.8f);
            filter.ApplyInPlace(bit2);
            AForge.Imaging.BlobCounter blobCounterGreen = new AForge.Imaging.BlobCounter();
            blobCounterGreen.FilterBlobs  = true;
            blobCounterGreen.ObjectsOrder = ObjectsOrder.Area;
            blobCounterGreen.MinHeight    = 10;
            blobCounterGreen.MinWidth     = 10;
            blobCounterGreen.ProcessImage(bit2);

            AForge.Imaging.Blob[] blobsGreen = blobCounterGreen.GetObjectsInformation();


            try
            {
                for (int iBlob = 0; iBlob < blobsGreen.Length; iBlob++)
                {
                    for (int jBlob = iBlob + 1; jBlob < blobsGreen.Length; jBlob++)
                    {
                        if ((Math.Abs(blobsGreen[iBlob].CenterOfGravity.X - blobsGreen[jBlob].CenterOfGravity.X) < blobsGreen[iBlob].Rectangle.Width / 2) &&
                            (Math.Abs(blobsGreen[iBlob].CenterOfGravity.Y - blobsGreen[jBlob].CenterOfGravity.Y) < 3 * blobsGreen[iBlob].Rectangle.Height) &&
                            (Math.Abs(blobsGreen[iBlob].Area - blobsGreen[jBlob].Area) < blobsGreen[iBlob].Area / 2))
                        {
                            //gameUpdate.Text = "OK" + SharedInformation.myNumber + getPlayerNumberByColor("Blue");
                            ortcExample.DoSendMessage(SharedInformation.myNumber + getPlayerNumberByColor("Blue"));
                            fin = true;
                            break;
                        }
                    }
                    if (fin)
                    {
                        break;
                    }
                }
            }
            catch (Exception es)
            {
                gameUpdate.Text = "erreur22";
            }
        }
示例#19
0
 // 如果活动返回值,则从 CodeActivity<TResult>
 // 派生并从 Execute 方法返回该值。
 protected override void Execute(CodeActivityContext context)
 {
     // create an instance of blob counter algorithm
     BlobCounterBase bc = new BlobCounter();
     // set filtering options
     bc.FilterBlobs = true;
     bc.MinWidth = context.GetValue(最小宽度);
     bc.MinHeight = context.GetValue(最小高度);
     // set ordering options
     bc.ObjectsOrder = ObjectsOrder.Size;
     // process binary image
     bc.ProcessImage(context.GetValue(处理目标));
     var blobs = bc.GetObjectsInformation();
     context.SetValue(输出目标, blobs);
 }
示例#20
0
        public static void Rectangle(WriteableBitmap bitmap, DrawingContext dc)
        {
            // locating objects
            BlobCounter blobCounter = new BlobCounter();
            blobCounter.FilterBlobs = true;
            blobCounter.MaxHeight = 375;
            blobCounter.MaxWidth = 375;
            System.Drawing.Bitmap image;
            using (var stream = new MemoryStream())
            {
                var encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bitmap));
                encoder.Save(stream);
                image = new System.Drawing.Bitmap(stream);
            }
            blobCounter.ProcessImage(image);
            Blob[] blobs = blobCounter.GetObjectsInformation();

            // check for rectangles
            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

            foreach (var blob in blobs)
            {
                List<IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blob);
                List<IntPoint> cornerPoints;

                // use the shape checker to extract the corner points
                if (shapeChecker.IsQuadrilateral(edgePoints, out cornerPoints))
                {
                    // only do things if the corners form a rectangle
                    if (shapeChecker.CheckPolygonSubType(cornerPoints) == PolygonSubType.Rectangle)
                    {
                        // here i use the graphics class to draw an overlay, but you
                        // could also just use the cornerPoints list to calculate your
                        // x, y, width, height values.
                        List<AForge.Point> Points = new List<AForge.Point>();
                        foreach (var point in cornerPoints)
                        {
                            Points.Add(new AForge.Point(point.X, point.Y));
                        }
                        var path = new PathFigure(new System.Windows.Point(Points.First().X, Points.First().Y), Points.Select(row => new System.Windows.Media.LineSegment(new System.Windows.Point(row.X, row.Y), false)), true);

                        dc.DrawGeometry(Brushes.Red, null, new PathGeometry(new PathFigure[] { path }));
                    }
                }
            }
        }
示例#21
0
        public ImageProcessor()
        {
            shapeChecker = new SimpleShapeChecker();
            hullFinder = new GrahamConvexHull();

            blobCounter = new BlobCounter();

            HotGoal = 0;

            greenPen = new Pen(Color.FromArgb(0, 255, 0), 1);
            yellowPen = new Pen(Color.FromArgb(255, 255, 0), 1);
            redPen = new Pen(Color.FromArgb(255, 0, 0), 2);
            orangePen = new Pen(Color.FromArgb(255, 127, 0), 1);
            purplePen = new Pen(Color.FromArgb(102, 51, 153), 1);
            redBrush = new SolidBrush(Color.FromArgb(255, 0, 0));
            blueBrush = new SolidBrush(Color.FromArgb(0, 0, 255));
        }
示例#22
0
        public KameraMyszka()
        {
            bc = new BlobCounter();
            bc.FilterBlobs = true;
            bc.MinWidth = 50;
            bc.MinHeight = 50;
            bc.ObjectsOrder = ObjectsOrder.Size;

            gestChance = new Dictionary<GEST, double>();

            /* coefficients for each hand */
            observed = new double[COEFF_COUNT, 2];

            InitializeComponent();
            globalHotkeys = new Hotkeys(HotkeysConstants.CTRL + HotkeysConstants.ALT + HotkeysConstants.SHIFT, Keys.Z, this);
            globalHotkeys2 = new Hotkeys(HotkeysConstants.CTRL + HotkeysConstants.ALT + HotkeysConstants.SHIFT, Keys.X, this);
        }
示例#23
0
        private WriteableBitmap FindPlate(IEnumerable<Rect> rects, WriteableBitmap image)
        {
            WriteableBitmap bestCandidate = null;
            
            foreach (var rect in rects)
            {
                var croppedImage = image.Crop(rect);
                var edgeFilter = new CannyEdgeDetector();
                var smoothFilter = new Median();
                var grayFilter = new Grayscale(0.2125, 0.7154, 0.0721);
                var blobCounter = new BlobCounter();
                var cutTop = croppedImage.PixelHeight * 0.3;

                croppedImage = croppedImage.Crop(new Rect(0, cutTop, croppedImage.PixelWidth, croppedImage.PixelHeight));

                var bitmap = (Bitmap)croppedImage;
                var grayImage = grayFilter.Apply(bitmap);

                bitmap = smoothFilter.Apply(grayImage);
                edgeFilter.ApplyInPlace(bitmap);
                blobCounter.ProcessImage(bitmap);

                var blobs = blobCounter.GetObjectsInformation();
                var possibleChars = new List<Rectangle>();

                foreach (var blob in blobs)
                {
                    var objRectangle = blob.Rectangle;
                    var ratio = (double)objRectangle.Height / (double)objRectangle.Width;
                    
                    if (ratio >= 1.16d && ratio <= 6.3d)
                    {
                        possibleChars.Add(objRectangle);
                    }
                }

                if (possibleChars.Count == 0)
                {
                    continue;
                }

                bestCandidate = croppedImage;
            }

            return bestCandidate;
        }
        private static Blob[] blobRecognition(Bitmap thresholdedInverted)
        {
            //Use the AForge.NET BlobCounter to perform Blob Recognition / Connected Region Analysis
            BlobCounter blobRecognition = new BlobCounter();

            //Filter out blobs that are abviously the wrong size to be characters
            blobRecognition.MinWidth = (int)(thresholdedInverted.Width * (BLOB_FILTER_MIN_DIMENSION_IMAGE_PERCENTAGE / 100));
            blobRecognition.MinHeight = (int)(thresholdedInverted.Height * (BLOB_FILTER_MIN_DIMENSION_IMAGE_PERCENTAGE / 100));
            blobRecognition.MaxWidth = (int)(thresholdedInverted.Width * (BLOB_FILTER_MAX_DIMENSION_IMAGE_PERCENTAGE / 100));
            blobRecognition.MaxHeight = (int)(thresholdedInverted.Height * (BLOB_FILTER_MAX_DIMENSION_IMAGE_PERCENTAGE / 100));
            blobRecognition.FilterBlobs = true;

            blobRecognition.ProcessImage(thresholdedInverted);
            Blob[] blobs = blobRecognition.GetObjectsInformation();

            return blobs;
        }
示例#25
0
        public IEnumerable<Bitmap> Apply(Bitmap bitmap)
        {
            // assuming scanned background is white we need to invert for the algo to work
            var copy = new Invert().Apply(bitmap);

            copy = EnsureGrayscale(copy);
            new Threshold { ThresholdValue = 25 }.ApplyInPlace(copy);
            new FillHoles().ApplyInPlace(copy);

            var blobCounter = new BlobCounter
            {
                // set filtering options
                FilterBlobs = true,
                MinWidth = 50,
                MinHeight = 50,
            };

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

            if (blobs.Any())
            {
                var invertedOriginal = new Invert().Apply(bitmap);
                foreach (var blob in blobs)
                {
                    // use inverted source to ensure correct edge colors
                    blobCounter.ExtractBlobsImage(invertedOriginal, blob, false);
                    var blobImage = blob.Image.ToManagedImage();

                    // straighten
                    var angle = new DocumentSkewChecker().GetSkewAngle(EnsureGrayscale(blobImage));
                    var rotationFilter = new RotateBilinear(-angle) { FillColor = Color.Black };
                    blobImage = rotationFilter.Apply(blobImage);

                    // crop
                    blobImage = new ExtractBiggestBlob().Apply(blobImage);

                    new Invert().ApplyInPlace(blobImage);
                    yield return blobImage;
                }
            }
            else
            {
                yield return bitmap;
            }
        }
        public void CountBlobs(string parsFileName)
        {
            Bitmap loBitmap;

            prsFileName = parsFileName;
            // Load the binary bitmap from the file
            loBitmap = (Bitmap)System.Drawing.Bitmap.FromFile(parsFileName);
            // Format the image according to AForge.NET needs to apply the filter
            AForge.Imaging.Image.FormatImage(ref loBitmap);
            // Create an instance of the blob counter algorithm
            AForge.Imaging.BlobCounter loBlobCounter = new AForge.Imaging.BlobCounter();
            // Process the binary image (find the blobs)
            loBlobCounter.ProcessImage(loBitmap);
            // Retrieve the array of found blobs and convert it to a List of Blob instances
            praoBlobs = loBlobCounter.GetObjects(loBitmap).ToList <Blob>();

            // Create a new image with a 24 bpp pixel format
            // We use System.Drawing.Image because there is also an AForge.Imaging.Image
            System.Drawing.Image loNewBitmap = new Bitmap(loBitmap.Width, loBitmap.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            // Create the graphics from the new image
            Graphics g = Graphics.FromImage((System.Drawing.Image)loNewBitmap);

            // Draw the image
            g.DrawImage(loBitmap, 0, 0);
            // Create the a new potential nebula list
            praoNebulaBlobs = new List <Blob>();
            using (Pen loPen = new Pen(Color.CornflowerBlue, 2))
            {
                // Process the blobs found in the image
                foreach (Blob loBlob in praoBlobs)
                {
                    if ((loBlob.Rectangle.Size.Width * loBlob.Rectangle.Size.Height) > 150)
                    {
                        // If the area is greater than 150 pixels, it is a potential nebula
                        praoNebulaBlobs.Add(loBlob);
                        // Draw a rectangle using the pen in the resulting image
                        g.DrawRectangle(loPen, loBlob.Rectangle);
                    }
                }
            }
            // Assign the generated bitmap to proBitmap
            proBitmap = (Bitmap)loNewBitmap;
            g.Dispose();

            //proBitmap.Save(prsFileName + "_OUT");
        }
示例#27
0
        public List<Blob> ExtractBlob()
        {
            // create instance of blob counter
            BlobCounter blobCounter = new BlobCounter();
            // process input image
            blobCounter.ProcessImage(ImageBitmap);
            
            // get information about detected objects   
            
            Blob[] blobArray = blobCounter.GetObjectsInformation();

            foreach(Blob blobdata in blobArray)
            {
                blobCounter.ExtractBlobsImage(ImageBitmap, blobdata, true);
            }
            
            return blobArray.ToList();
        }
示例#28
0
        public static FoundBlobs FindAny(FoundColorSpaces colorSpaces)
        {
            FoundBlobs foundBlobs = new FoundBlobs();

            SobelEdgeDetector edge = new SobelEdgeDetector();
            Bitmap edges = edge.Apply(colorSpaces.GrayColorSpace);

            Threshold threshold = new Threshold(50);
            threshold.ApplyInPlace(edges);

            BlobCounter blobCounter = new BlobCounter();
            blobCounter.ProcessImage(edges);
            foundBlobs.Blobs = blobCounter.GetObjects(colorSpaces.GrayColorSpace, false).ToArray();

            foundBlobs.BlobCounter = blobCounter;

            return foundBlobs;
        }
示例#29
0
        //Bitmap Source to Bitmap Convertor End
        //Blob Counter Start
        public Blob[] blobcounter(BitmapSource bsource)
        {
            System.Drawing.Bitmap b = BitmapFromSource(bsource);

            BlobCounter BCounter = new BlobCounter();

            ColorFiltering FilterObjects = new ColorFiltering();

            BCounter.FilterBlobs = true;
            BCounter.MinWidth = 50;
            BCounter.MinHeight = 50;

            BCounter.ProcessImage(b);

            Blob[] detectedblobs = BCounter.GetObjectsInformation();

            return detectedblobs;
        }
        Blob[] DetectBlobs(Bitmap bmp)
        {
            Invert filter = new Invert();
            filter.ApplyInPlace(bmp);

            BlobCounter bc = new BlobCounter();
            bc.BackgroundThreshold = Color.FromArgb(8, 8, 8);

            bc.BlobsFilter = new BlobsFilter(bmp.Size);
            bc.FilterBlobs = true;

            bc.ProcessImage(bmp);

            // Revert back
            filter.ApplyInPlace(bmp);

            return bc.GetObjectsInformation();
        }
示例#31
0
        // Process specified image trying to recognize counter's image
        public void Process(Bitmap image, IImageProcessingLog log)
        {
            log.AddMessage("Image size: " + image.Width +
                 " x " + image.Height);

            //get image
            byte[] textData = GetImageData();
            UnmanagedImage img = CreateImage(textData);
            log.AddImage("Raw Image", img.ToManagedImage());

            //resize Image
            AForge.Imaging.Filters.ResizeNearestNeighbor resizeFilter = new AForge.Imaging.Filters.ResizeNearestNeighbor(500, (int)(500 / res));
            UnmanagedImage resizedImage = resizeFilter.Apply(img);
            log.AddImage("Resized Image", resizedImage.ToManagedImage());
            
            //filter floor
            UnmanagedImage floorFilteredImage = FilterFloor(resizedImage, textData);
            log.AddImage("Floor filtered", floorFilteredImage.ToManagedImage());

            // 1- grayscale image
            Bitmap grayImage =
                 Grayscale.CommonAlgorithms.BT709.Apply(resizedImage.ToManagedImage());
            log.AddImage("Grayscale", resizedImage.ToManagedImage());

            // 2 - Otsu thresholding
            OtsuThreshold threshold = new OtsuThreshold();
            Bitmap binaryImage = threshold.Apply(grayImage);
            log.AddImage("Binary", binaryImage);
            log.AddMessage("Otsu threshold: " + threshold.ThresholdValue);
            //resive image

            // 3 - Blob counting
            BlobCounter blobCounter = new BlobCounter();
            blobCounter.FilterBlobs = true;
            blobCounter.MinWidth = 1;
            blobCounter.MinWidth = 1;

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

            log.AddMessage("Found blobs (min width/height = 24): " +
                 blobs.Length);

        }
示例#32
0
        public Bitmap ProcessFrame(Bitmap inputBitmap, int x, int y)
        {
            // Create an image for AForge to process
            Bitmap workingImage = new Bitmap(inputBitmap.Width, inputBitmap.Height);
            workingImage = AForge.Imaging.Image.Clone(inputBitmap, PixelFormat.Format24bppRgb);

            // Create a mask for ROI selection
            Rectangle roi = new Rectangle(x - 30, y-30, 80, 80);

            Crop roicrop = new Crop(roi);
            Bitmap outimage = roicrop.Apply(workingImage);

            BlobCounter blobCounter = new BlobCounter();
            blobCounter.ObjectsOrder = ObjectsOrder.Area;

            Blob[] blobs;

            // Find the blobs
            blobCounter.ProcessImage(outimage);
            blobs = blobCounter.GetObjectsInformation();
            List<IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[0]);

            GrahamConvexHull grahamScan = new GrahamConvexHull();
            List<IntPoint> hullPoints = grahamScan.FindHull(edgePoints);

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

            g.DrawPolygon(redPen, ToPointsArray(hullPoints));

            //g.Clear(Color.Black);
            //g.DrawImage(handImage, x, y);
            //g.DrawRectangle(redPen, roi);
            //g.DrawEllipse(redPen, x, y, 20, 20);

            ResizeNearestNeighbor resizeFilter = new ResizeNearestNeighbor(160, 160);
            Bitmap resizedImage = resizeFilter.Apply(outimage);

            return resizedImage;
        }
        //1. bright pixel / dark pixel
        //2.lowest gray level
        //3.highest gray level
        //4.number of peaks in the x direction.
        //5.number of peaks in the y direction.
        public static double[] ExtractFeatures(Bitmap bmp,int i)
        {
            //Apply GrayScale
            GrayscaleBT709 greyScaleFilter = new GrayscaleBT709();
            Bitmap newBmp = greyScaleFilter.Apply((Bitmap)bmp.Clone());

            //Count Blobs
            BlobCounter blobCounter = new BlobCounter();
            blobCounter.BackgroundThreshold = Color.FromArgb(255, 150, 150, 150);
            blobCounter.ProcessImage(newBmp);
            int blobs = (blobCounter.ObjectsCount - 1) * 30;

            //Count Corner
            SusanCornersDetector scd = new SusanCornersDetector();
            scd.DifferenceThreshold = 70;
            scd.GeometricalThreshold = 8;
            int corners = scd.ProcessImage((Bitmap)newBmp.Clone()).Count();

            //Apply Edge Filter
            CannyEdgeDetector filter = new CannyEdgeDetector();
            //newBmp = filter.Apply(newBmp);
            Histogram his = new HorizontalIntensityStatistics(newBmp).Gray;
            Histogram vis = new VerticalIntensityStatistics(newBmp).Gray;

            HoughLineTransformation lineTransform = new HoughLineTransformation();
            // apply Hough line transofrm
            lineTransform.ProcessImage(filter.Apply(newBmp));
            Bitmap houghLineImage = lineTransform.ToBitmap();
            // get lines using relative intensity
            HoughLine[] lines = lineTransform.GetLinesByRelativeIntensity(1);
            int linesCount = lines.Count() * 30;

            double[] features = new double[13] { blobs, corners, his.Max, his.Min, his.Mean, his.Median, his.StdDev,
                vis.Max, vis.Min, vis.Mean, vis.Median, vis.StdDev,linesCount};

            //double[] features = new double[3] { blobs, corners,lines};

            newBmp.Save(String.Format("test{0}.bmp",i));
            return features;
        }
示例#34
0
        public static List<List<IntPoint>> Quadrilaterals(Bitmap img, int minWidth, int minHeight)
        {
            Bitmap thresholdedImg = FilterCombinations.AdaptiveThreshold(img);

            //Use blob recognition on the image to find all blobs meeting the specified minimum width & height
            BlobCounter blobCounter = new BlobCounter();

            //Filter out small blobs
            blobCounter.MinWidth = minWidth;
            blobCounter.MinHeight = minHeight;
            blobCounter.FilterBlobs = true;

            //Order the blobs by size (desc), as since we're looking for quads of a minimum size, it's likely we'll be more interested in the laregr ones
            blobCounter.ObjectsOrder = ObjectsOrder.Size;

            //Check if each blob is approximately a quadriateral, and if so store the 4 corners
            List<List<IntPoint>> foundQuads = new List<List<IntPoint>>();
            //Shape checker to be used to test if a blob is a quadrilateral
            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

            //Find the blobs
            blobCounter.ProcessImage(thresholdedImg);
            Blob[] blobs = blobCounter.GetObjectsInformation();

            foreach(Blob b in blobs)
            {
                List<IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(b);
                List<IntPoint> corners = null;

                //Is this blob approximately a quadrilateral?
                if(shapeChecker.IsQuadrilateral(edgePoints, out corners))
                {
                    //Store the Quad's corners
                    foundQuads.Add(corners);
                }
            }

            return foundQuads;
        }
示例#35
0
        public List<Blob> ExtractBlob(int maxWidth, int maxHeight, int minWidth, int minHeight)
        {
            BlobCounter blobCounter = new BlobCounter();
            blobCounter.MinHeight = minHeight;
            blobCounter.MinWidth = minWidth;
            blobCounter.MaxWidth = maxWidth;
            blobCounter.MaxHeight = maxHeight;
            blobCounter.FilterBlobs = true;
            // process input image
            blobCounter.ProcessImage(ImageBitmap);

            // get information about detected objects   

            Blob[] blobArray = blobCounter.GetObjectsInformation();

            foreach (Blob blobdata in blobArray)
            {
                blobCounter.ExtractBlobsImage(ImageBitmap, blobdata, true);
            }

            return blobArray.ToList();
        }        
示例#36
0
        public static AForge.Point GetRedBlobCenter(Bitmap image)
        {
            BlobCounter bCounter = new BlobCounter();
            bCounter.ProcessImage(image);

            Blob[] blobs = bCounter.GetObjectsInformation();
            Rectangle[] rects = bCounter.GetObjectsRectangles();

            Pen pen = new Pen(Color.Red, 2);
            Brush brush = new SolidBrush(Color.Red);
            Graphics g = Graphics.FromImage(image);

            if (rects.Length > 0) { g.FillRectangle(brush, rects[0]); }

            if (blobs.Length > 0)
            {

                detected = true;
                lastPos = blobs[0].CenterOfGravity;

                AForge.Point rPos = new AForge.Point();
                rPos.Y = ((lastPos.Y / 5) / 100) * 768;
                rPos.X = ((lastPos.X / 5) / 100) * 1366;

                return rPos;
            }
            else
            {
                detected = false;
                if (lastPos != null)
                {
                    return lastPos;
                }
                else
                {
                    return new AForge.Point(50.0f, 50.0f);
                }
            }
        }
示例#37
0
        public Boolean ContainOrange(Bitmap bitmap)
        {
            ColorFiltering RedFilter = new ColorFiltering();

            RedFilter.Red   = new IntRange(100, 255);
            RedFilter.Green = new IntRange(0, 100);
            RedFilter.Blue  = new IntRange(0, 100);
            RedFilter.ApplyInPlace(bitmap);
            AForge.Imaging.BlobCounter blobCounterGreen = new AForge.Imaging.BlobCounter();

            blobCounterGreen.FilterBlobs = true;
            blobCounterGreen.MinHeight   = 5;
            blobCounterGreen.MinWidth    = 5;
            blobCounterGreen.ProcessImage(bitmap);
            AForge.Imaging.Blob[] blobsGreen        = blobCounterGreen.GetObjectsInformation();
            SimpleShapeChecker    shapeCheckerGreen = new SimpleShapeChecker();

            if (blobsGreen.Length > 0)
            {
                return(true);
            }
            return(false);
        }
示例#38
0
        public String ContainRed(Bitmap bitmap)
        {
            HSLFiltering filterRed = new HSLFiltering();

            filterRed.Hue        = new IntRange(301, 9);   //red at night (334, 40)
            filterRed.Saturation = new Range(0.4f, 1);     //0.55
            filterRed.Luminance  = new Range(0.1f, 0.68f); //75
            filterRed.ApplyInPlace(bitmap);

            AForge.Imaging.BlobCounter blobCounterRed = new AForge.Imaging.BlobCounter();
            blobCounterRed.FilterBlobs  = true;
            blobCounterRed.ObjectsOrder = ObjectsOrder.Area;
            blobCounterRed.MinHeight    = 10;
            blobCounterRed.MinWidth     = 10;
            blobCounterRed.ProcessImage(bitmap);

            AForge.Imaging.Blob[] blobsRed = blobCounterRed.GetObjectsInformation();
            //capturedPhotoRed.Source = (WriteableBitmap)bitmap;
            //Mean filter = new Mean();
            //// apply the filter
            //filter.ApplyInPlace(bitmap);
            for (int iBlob = 0; iBlob < blobsRed.Length; iBlob++)
            {
                for (int jBlob = iBlob + 1; jBlob < blobsRed.Length; jBlob++)
                {
                    if ((Math.Abs(blobsRed[iBlob].CenterOfGravity.X - blobsRed[jBlob].CenterOfGravity.X) < blobsRed[iBlob].Rectangle.Width / 2) &&
                        (Math.Abs(blobsRed[iBlob].CenterOfGravity.Y - blobsRed[jBlob].CenterOfGravity.Y) < 3 * blobsRed[iBlob].Rectangle.Height) &&
                        (Math.Abs(blobsRed[iBlob].Area - blobsRed[jBlob].Area) < blobsRed[iBlob].Area / 2))
                    {
                        //try { text_log.Text += "i" + iBlob + "j" + jBlob + "diff" + Math.Abs(blobsRed[iBlob].CenterOfGravity.X - blobsRed[jBlob].CenterOfGravity.X) + "w" + blobsRed[iBlob].Rectangle.Width / 2; }
                        //catch (Exception ex) { text_log.Text = ex + ""; }
                        return("red");
                    }
                }
            }
            return("");
        }
示例#39
0
        public String ContainPurple(Bitmap bitmap)
        {
            HSLFiltering filter = new HSLFiltering();

            // set color ranges to keep
            filter.Hue        = new IntRange(220, 290);
            filter.Saturation = new Range(0.4f, 0.8f);
            filter.Luminance  = new Range(0.35f, 0.78f);
            filter.ApplyInPlace(bitmap);

            AForge.Imaging.BlobCounter blobCounterPutple = new AForge.Imaging.BlobCounter();
            blobCounterPutple.FilterBlobs  = true;
            blobCounterPutple.ObjectsOrder = ObjectsOrder.Area;
            blobCounterPutple.MinHeight    = 10;
            blobCounterPutple.MinWidth     = 10;
            blobCounterPutple.ProcessImage(bitmap);
            AForge.Imaging.Blob[] blobsPurple        = blobCounterPutple.GetObjectsInformation();
            SimpleShapeChecker    shapeCheckerPurple = new SimpleShapeChecker();

            //capturedPhotoBlue.Source = (WriteableBitmap)bitmap;
            for (int iBlob = 0; iBlob < blobsPurple.Length; iBlob++)
            {
                for (int jBlob = iBlob + 1; jBlob < blobsPurple.Length; jBlob++)
                {
                    if ((Math.Abs(blobsPurple[iBlob].CenterOfGravity.X - blobsPurple[jBlob].CenterOfGravity.X) < blobsPurple[iBlob].Rectangle.Width / 2) &&
                        (Math.Abs(blobsPurple[iBlob].CenterOfGravity.Y - blobsPurple[jBlob].CenterOfGravity.Y) < 3 * blobsPurple[iBlob].Rectangle.Height) &&
                        (Math.Abs(blobsPurple[iBlob].Area - blobsPurple[jBlob].Area) < blobsPurple[iBlob].Area / 2))
                    {
                        //try { text_log.Text += "i" + iBlob + "j" + jBlob + "diff" + Math.Abs(blobsPurple[iBlob].CenterOfGravity.X - blobsPurple[jBlob].CenterOfGravity.X) + "w" + blobsPurple[iBlob].Rectangle.Width / 2; }
                        //catch (Exception ex) { text_log.Text = ex + ""; }
                        return("Purple");
                    }
                }
            }
            return("");
        }
示例#40
0
        public bool markKnownForms()
        {
            if (currentImage != null)
            {
                try
                {
                    Bitmap image = new Bitmap(this.currentImage);
                    // lock image
                    BitmapData bmData = image.LockBits(
                        new Rectangle(0, 0, image.Width, image.Height),
                        ImageLockMode.ReadWrite, image.PixelFormat);

                    // turn background to black
                    ColorFiltering cFilter = new ColorFiltering();
                    cFilter.Red = new IntRange(0, 64);
                    cFilter.Green = new IntRange(0, 64);
                    cFilter.Blue = new IntRange(0, 64);
                    cFilter.FillOutsideRange = false;
                    cFilter.ApplyInPlace(bmData);

                    // locate objects
                    BlobCounter bCounter = new BlobCounter();

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

                    bCounter.ProcessImage(bmData);

                    numberOfShellsDetected = bCounter.ObjectsCount;

                    Blob[] baBlobs = bCounter.GetObjectsInformation();
                    image.UnlockBits(bmData);

                    // coloring objects
                    SimpleShapeChecker shapeChecker = new SimpleShapeChecker();

                    Graphics g = Graphics.FromImage(image);
                    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 = baBlobs.Length; i < n; i++)
                    {
                        List<IntPoint> edgePoints = bCounter.GetBlobsEdgePoints(baBlobs[i]);
                        foreach (IntPoint point in edgePoints)
                            g.DrawEllipse(redPen, point.X, point.Y, 2, 2);

                        /*AForge.Point center;
                        float radius;

                        // is circle ?
                        if (shapeChecker.IsCircle(edgePoints, out center, out radius))
                        {
                            numberOfShellsDetected++;
                            g.DrawEllipse(redPen,
                                (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))
                            {
                                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();
                    this.currentImage = image;
                    return true;
                }
                catch (Exception e)
                {

                }
            }
            return false;
        }
示例#41
0
        public static IEnumerable<MagicCard> DetectCardArt(Bitmap cameraBitmap)
        {
            var ret = new List<MagicCard>();

            var filteredBitmap = Grayscale.CommonAlgorithms.BT709.Apply(cameraBitmap);

            // edge filter
            var edgeFilter = new SobelEdgeDetector();
            edgeFilter.ApplyInPlace(filteredBitmap);

            // Threshhold filter
            var threshholdFilter = new Threshold(190);
            threshholdFilter.ApplyInPlace(filteredBitmap);

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

            var blobCounter = new BlobCounter();

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

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

            var shapeChecker = new SimpleShapeChecker();
            var bm = new Bitmap(filteredBitmap.Width, filteredBitmap.Height, PixelFormat.Format24bppRgb);

            var cardPositions = new List<IntPoint>();
            foreach (var blob in blobs)
            {
                var edgePoints = blobCounter.GetBlobsEdgePoints(blob);

                List<IntPoint> corners;

                // only operate on 4 sided polygons
                if (shapeChecker.IsConvexPolygon(edgePoints, out corners))
                {
                    var subtype = shapeChecker.CheckPolygonSubType(corners);

                    if (corners.Count() != 4)
                        continue;

                    if (subtype != PolygonSubType.Parallelogram && subtype != PolygonSubType.Rectangle)
                        continue;

                    // if the image is sideways, rotate it so it'll match the DB card art
                    corners = Utilities.RotateCorners(corners).ToList();

                    if (Utilities.GetArea(corners) < 20000)
                        continue;

                    ret.Add( new MagicCard(cameraBitmap, corners));
                }
            }

            return ret;
        }
示例#42
0
        // Get array of objects rectangles
        public static Rectangle[] GetObjectRectangles(Bitmap srcImg)
        {
            BlobCounter blobCounter = new BlobCounter();

            // process the image
            blobCounter.ProcessImage(srcImg);

            int[] labels = blobCounter.ObjectLabels;
            int   count  = blobCounter.ObjectsCount;

            // image size
            int width = srcImg.Width;
            int height = srcImg.Height;
            int i = 0, label;

            // create object coordinates arrays
            int[] x1 = new int[count + 1];
            int[] y1 = new int[count + 1];
            int[] x2 = new int[count + 1];
            int[] y2 = new int[count + 1];

            for (int j = 1; j <= count; j++)
            {
                x1[j] = width;
                y1[j] = height;
            }

            // walk through labels array
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++, i++)
                {
                    // get current label
                    label = labels[i];

                    // skip unlabeled pixels
                    if (label == 0)
                    {
                        continue;
                    }

                    // check and update all coordinates

                    if (x < x1[label])
                    {
                        x1[label] = x;
                    }
                    if (x > x2[label])
                    {
                        x2[label] = x;
                    }
                    if (y < y1[label])
                    {
                        y1[label] = y;
                    }
                    if (y > y2[label])
                    {
                        y2[label] = y;
                    }
                }
            }

            // create rectangles
            Rectangle[] rects = new Rectangle[count];

            for (int j = 1; j <= count; j++)
            {
                rects[j - 1] = new Rectangle(x1[j], y1[j], x2[j] - x1[j] + 1, y2[j] - y1[j] + 1);
            }

            return(rects);
        }
示例#43
0
        // Get array of objects images
        public static Blob[] GetObjects(Bitmap srcImg)
        {
            BlobCounter blobCounter = new BlobCounter();

            // process the image
            blobCounter.ProcessImage(srcImg);

            int[] labels = blobCounter.ObjectLabels;
            int   count  = blobCounter.ObjectsCount;

            // image size
            int width = srcImg.Width;
            int height = srcImg.Height;
            int i = 0, label;

            // --- STEP 1 - find each objects coordinates

            // create object coordinates arrays
            int[] x1 = new int[count + 1];
            int[] y1 = new int[count + 1];
            int[] x2 = new int[count + 1];
            int[] y2 = new int[count + 1];

            for (int k = 1; k <= count; k++)
            {
                x1[k] = width;
                y1[k] = height;
            }

            // walk through labels array
            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++, i++)
                {
                    // get current label
                    label = labels[i];

                    // skip unlabeled pixels
                    if (label == 0)
                    {
                        continue;
                    }

                    // check and update all coordinates

                    if (x < x1[label])
                    {
                        x1[label] = x;
                    }
                    if (x > x2[label])
                    {
                        x2[label] = x;
                    }
                    if (y < y1[label])
                    {
                        y1[label] = y;
                    }
                    if (y > y2[label])
                    {
                        y2[label] = y;
                    }
                }
            }

            // --- STEP 2 - get each object
            Blob[] objects = new Blob[count];

            // lock source bitmap data
            BitmapData srcData = srcImg.LockBits(
                new Rectangle(0, 0, width, height),
                ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);

            int srcStride = srcData.Stride;

            // create each image
            for (int k = 1; k <= count; k++)
            {
                int xmin         = x1[k];
                int xmax         = x2[k];
                int ymin         = y1[k];
                int ymax         = y2[k];
                int objectWidth  = xmax - xmin + 1;
                int objectHeight = ymax - ymin + 1;

                // create new image
                Bitmap dstImg = AForge.Imaging.Image.CreateGrayscaleImage(objectWidth, objectHeight);

                // lock destination bitmap data
                BitmapData dstData = dstImg.LockBits(
                    new Rectangle(0, 0, objectWidth, objectHeight),
                    ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);

                // copy image
                unsafe
                {
                    byte *src = (byte *)srcData.Scan0.ToPointer() + ymin * srcStride + xmin;
                    byte *dst = (byte *)dstData.Scan0.ToPointer();
                    int   p   = ymin * width + xmin;

                    int srcOffset    = srcStride - objectWidth;
                    int dstOffset    = dstData.Stride - objectWidth;
                    int labelsOffset = width - objectWidth;

                    // for each line
                    for (int y = ymin; y <= ymax; y++)
                    {
                        // copy each pixel
                        for (int x = xmin; x <= xmax; x++, src++, dst++, p++)
                        {
                            if (labels[p] == k)
                            {
                                *dst = *src;
                            }
                        }
                        src += srcOffset;
                        dst += dstOffset;
                        p   += labelsOffset;
                    }
                }
                // unlock destination image
                dstImg.UnlockBits(dstData);

                objects[k - 1] = new Blob(dstImg, new Point(xmin, ymin), srcImg);
            }

            // unlock source image
            srcImg.UnlockBits(srcData);

            return(objects);
        }
示例#44
0
        private void btnMassAnalysis_Click(object sender, RoutedEventArgs e)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            for (int index = 0; index < 6; index++)
            {
                string folderSettingText = "";

                switch (index)
                {
                case 0:
                    folderSettingText = "Batch 1\\All Top";
                    break;

                case 1:
                    folderSettingText = "Batch 2\\All Top";
                    break;

                case 2:
                    folderSettingText = "Batch 3\\All Top";
                    break;

                case 3:
                    folderSettingText = "Batch 1\\All Bottom";
                    break;

                case 4:
                    folderSettingText = "Batch 2\\All Bottom";
                    break;

                case 5:
                    folderSettingText = "Batch 3\\All Bottom";
                    break;

                default:
                    folderSettingText = "";
                    break;
                }
                string[] filename = { "" };
                //string path = @"E:\Brian\Project 3 - English Muffin Onsite Data Gathering\SK Foods On-Site Scan\English Muffin\Batch 3\All Bottom";


                string path          = "C:\\Users\\kai23\\Projects\\ABI\\EnglishMuffinVision_AForge\\Images\\English Muffin\\" + folderSettingText;
                string searchPattern = "æKatanaScoring_CameraImageGray1*";
                try
                {
                    filename = Directory.GetFiles(path, searchPattern, SearchOption.AllDirectories);
                }
                catch (UnauthorizedAccessException)
                {
                }

                foreach (string f in filename)
                {
                    if (f != null)
                    {
                        GrayScaleImage = AForge.Imaging.Image.FromFile(f);

                        int    startPos = f.LastIndexOf("SK Foods On-Site Scan") + "SK Foods On-Site Scan".Length + 1;
                        int    length   = f.IndexOf("æ") - startPos - 1;
                        string sub      = f.Substring(startPos, length);

                        lblFolder.Content = sub;
                        //AForge.Imaging.UnmanagedImage unmanagedImage1 = AForge.Imaging.UnmanagedImage.FromManagedImage(GrayScaleImage);
                        //Bitmap managedImage = unmanagedImage1.ToManagedImage();
                        //BitmapImage GrayImage_temp = ToBitmapImage(managedImage);
                        //imgGray.Source = GrayImage_temp;

                        //Stopwatch stopwatch = new Stopwatch();
                        //stopwatch.Start();

                        AForge.Imaging.UnmanagedImage unmanagedImage1 = AForge.Imaging.UnmanagedImage.FromManagedImage(GrayScaleImage);
                        AForge.Imaging.BlobCounter    bc = new AForge.Imaging.BlobCounter
                        {
                            CoupledSizeFiltering = true,
                            FilterBlobs          = true,
                            MinHeight            = 30,
                            MinWidth             = 30,
                            MaxHeight            = 100,
                            MaxWidth             = 100
                        };

                        bc.ProcessImage(GrayScaleImage);

                        lblBlobCount.Content = bc.ObjectsCount;

                        Bitmap indexMap = AForge.Imaging.Image.Clone(GrayScaleImage);

                        for (int x = 0; x < indexMap.Width; x++)
                        {
                            for (int y = 0; y < indexMap.Height; y++)
                            {
                                indexMap.SetPixel(x, y, System.Drawing.Color.Black);
                            }
                        }

                        System.Drawing.Rectangle[] rects = bc.GetObjectsRectangles();
                        // process blobs
                        BreadBlob[] breadBlob1     = new BreadBlob[bc.ObjectsCount];
                        int         blobArrayIndex = 0;
                        int         blobPt         = Convert.ToInt16(txbBlobNum.Text);
                        int         blobThreshold  = Convert.ToInt16(txbBlobThreshold.Text);
                        if (blobPt >= bc.ObjectsCount)
                        {
                            blobPt = bc.ObjectsCount - 1;
                        }
                        StaticsCalculator MuffinStatistics = new StaticsCalculator();

                        Graphics g = Graphics.FromImage(indexMap);
                        foreach (System.Drawing.Rectangle rect in rects)
                        {
                            //initialize Object
                            breadBlob1[blobArrayIndex] = new BreadBlob();
                            breadBlob1[blobArrayIndex].TopDownThreshold = blobThreshold;
                            byte[,] blobArray = new byte[rect.Width, rect.Height];

                            for (int x = rect.Left; x < rect.Right; x++)
                            {
                                for (int y = rect.Top; y < rect.Bottom; y++)
                                {
                                    System.Drawing.Color tempPixelColor = GrayScaleImage.GetPixel(x, y);
                                    blobArray[x - rect.Left, y - rect.Top] = tempPixelColor.G;
                                }
                            }

                            breadBlob1[blobArrayIndex].PixelArray = blobArray;
                            breadBlob1[blobArrayIndex].X          = rect.X;
                            breadBlob1[blobArrayIndex].Y          = rect.Y;
                            MuffinStatistics.Add(breadBlob1[blobArrayIndex].Variance.QAverage);

                            if (blobArrayIndex == blobPt)
                            {
                                System.Drawing.Rectangle tempRect = rect;
                                tempRect.X      -= 1;
                                tempRect.Y      -= 1;
                                tempRect.Width  += 2;
                                tempRect.Height += 2;

                                AForge.Imaging.Drawing.Rectangle(unmanagedImage1, tempRect, System.Drawing.Color.Yellow);
                            }

                            if (breadBlob1[blobArrayIndex].IsTop())
                            {
                                AForge.Imaging.Drawing.Rectangle(unmanagedImage1, rect, System.Drawing.Color.Green);
                            }
                            else
                            {
                                AForge.Imaging.Drawing.Rectangle(unmanagedImage1, rect, System.Drawing.Color.Red);
                            }

                            RectangleF rectf = new RectangleF(rect.X, rect.Y, rect.Width, rect.Height);

                            g.SmoothingMode     = SmoothingMode.AntiAlias;
                            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                            g.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                            g.DrawString(Convert.ToString(blobArrayIndex), new Font("Arial", 5), System.Drawing.Brushes.White, rectf);

                            lblBlobHeight.Content = rect.Height;
                            lblBlobWidth.Content  = rect.Width;

                            blobArrayIndex++;
                        }

                        BitmapImage indexMap_temp = ToBitmapImage(indexMap);
                        g.Flush();
                        // conver to managed image if it is required to display it at some point of time
                        Bitmap managedImage = unmanagedImage1.ToManagedImage();

                        // create filter
                        Add filter = new Add(indexMap);
                        // apply the filter
                        Bitmap      resultImage    = filter.Apply(managedImage);
                        BitmapImage GrayImage_temp = ToBitmapImage(resultImage);

                        imgGray.Source = GrayImage_temp;



                        lblLib.Content           = "AForge";
                        lblVariance.Content      = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.All);
                        lblX.Content             = breadBlob1[blobPt].X;
                        lblY.Content             = breadBlob1[blobPt].Y;
                        lblQ1Variance.Content    = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.Q1);
                        lblQ2Variance.Content    = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.Q2);
                        lblQ3Variance.Content    = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.Q3);
                        lblQ4Variance.Content    = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.Q4);
                        lblQAverage.Content      = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.QAverage);
                        lblAllMuffinStat.Content = MuffinStatistics.StandardDeviation;


                        // System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\Histogram.txt", GrayImage1Histogram_str);
                        // E:\Brian\Project 3 - English Muffin Onsite Data Gathering\Data Analysis
                        //System.IO.File.WriteAllLines(@"E:\Brian\Project 3 - English Muffin Onsite Data Gathering\Data Analysis\Histogram.txt", GrayImage1Histogram_str);

                        bool fileExist = File.Exists("C:\\Users\\kai23\\Projects\\ABI\\EnglishMuffinVision_AForge\\Data Analysis\\Data.csv");

                        using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\kai23\Projects\ABI\EnglishMuffinVision_AForge\Data Analysis\Data.csv", true))
                        {
                            if (!fileExist)
                            {
                                file.WriteLine("File Info," +
                                               "Variance All," +
                                               "Vari Q1:," +
                                               "Vari Q2:," +
                                               "Vari Q3:," +
                                               "Vari Q4:," +
                                               "Variance Average:," +
                                               "S1," +
                                               "S2," +
                                               "S3," +
                                               "S4," +
                                               "S5," +
                                               "S6," +
                                               "S7," +
                                               "S8," +
                                               "S9," +
                                               "Savg," +
                                               "L1," +
                                               "L2," +
                                               "L3," +
                                               "L4," +
                                               "L5," +
                                               "L6," +
                                               "L7," +
                                               "L8," +
                                               "L9," +
                                               "L10," +
                                               "L11," +
                                               "L12," +
                                               "L13," +
                                               "L14," +
                                               "L15," +
                                               "L16," +
                                               "Lavg");
                            }

                            file.WriteLine(Convert.ToString(lblFolder.Content) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.All)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.Q1)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.Q2)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.Q3)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.Q4)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.QAverage)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.S1)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.S2)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.S3)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.S4)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.S5)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.S6)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.S7)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.S8)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.S9)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.Savg)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.L1)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.L2)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.L3)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.L4)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.L5)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.L6)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.L7)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.L8)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.L9)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.L10)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.L11)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.L12)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.L13)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.L14)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.L15)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.L16)) + "," +
                                           Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.Lavg)));
                        }

                        //lblFolder.Content = "";
                    }
                }
            }
            stopwatch.Stop();
            lblTime.Content = stopwatch.ElapsedMilliseconds;
        }
示例#45
0
        private void BtnCalculate_Click(object sender, RoutedEventArgs e)
        {
            if (imageLoaded)
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();

                AForge.Imaging.UnmanagedImage unmanagedImage1 = AForge.Imaging.UnmanagedImage.FromManagedImage(GrayScaleImage);
                AForge.Imaging.BlobCounter    bc = new AForge.Imaging.BlobCounter
                {
                    CoupledSizeFiltering = true,
                    FilterBlobs          = true,
                    MinHeight            = 30,
                    MinWidth             = 30,
                    MaxHeight            = 100,
                    MaxWidth             = 100
                };

                bc.ProcessImage(GrayScaleImage);

                lblBlobCount.Content = bc.ObjectsCount;

                Bitmap indexMap = AForge.Imaging.Image.Clone(GrayScaleImage);

                for (int x = 0; x < indexMap.Width; x++)
                {
                    for (int y = 0; y < indexMap.Height; y++)
                    {
                        indexMap.SetPixel(x, y, System.Drawing.Color.Black);
                    }
                }

                System.Drawing.Rectangle[] rects = bc.GetObjectsRectangles();
                // process blobs
                BreadBlob[] breadBlob1     = new BreadBlob[bc.ObjectsCount];
                int         blobArrayIndex = 0;
                int         blobPt         = Convert.ToInt16(txbBlobNum.Text);
                int         blobThreshold  = Convert.ToInt16(txbBlobThreshold.Text);
                if (blobPt >= bc.ObjectsCount)
                {
                    blobPt = bc.ObjectsCount - 1;
                }
                StaticsCalculator MuffinStatistics = new StaticsCalculator();

                Graphics g = Graphics.FromImage(indexMap);
                foreach (System.Drawing.Rectangle rect in rects)
                {
                    //initialize Object
                    breadBlob1[blobArrayIndex] = new BreadBlob();
                    breadBlob1[blobArrayIndex].TopDownThreshold = blobThreshold;
                    byte[,] blobArray = new byte[rect.Width, rect.Height];

                    for (int x = rect.Left; x < rect.Right; x++)
                    {
                        for (int y = rect.Top; y < rect.Bottom; y++)
                        {
                            System.Drawing.Color tempPixelColor = GrayScaleImage.GetPixel(x, y);
                            blobArray[x - rect.Left, y - rect.Top] = tempPixelColor.G;
                        }
                    }

                    breadBlob1[blobArrayIndex].PixelArray = blobArray;
                    breadBlob1[blobArrayIndex].X          = rect.X;
                    breadBlob1[blobArrayIndex].Y          = rect.Y;
                    MuffinStatistics.Add(breadBlob1[blobArrayIndex].Variance.QAverage);

                    if (blobArrayIndex == blobPt)
                    {
                        System.Drawing.Rectangle tempRect = rect;
                        tempRect.X      -= 1;
                        tempRect.Y      -= 1;
                        tempRect.Width  += 2;
                        tempRect.Height += 2;

                        AForge.Imaging.Drawing.Rectangle(unmanagedImage1, tempRect, System.Drawing.Color.Yellow);
                    }

                    if (breadBlob1[blobArrayIndex].IsTop())
                    {
                        AForge.Imaging.Drawing.Rectangle(unmanagedImage1, rect, System.Drawing.Color.Green);
                    }
                    else
                    {
                        AForge.Imaging.Drawing.Rectangle(unmanagedImage1, rect, System.Drawing.Color.Red);
                    }

                    RectangleF rectf = new RectangleF(rect.X, rect.Y, rect.Width, rect.Height);

                    g.SmoothingMode     = SmoothingMode.AntiAlias;
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                    g.DrawString(Convert.ToString(blobArrayIndex), new Font("Arial", 5), System.Drawing.Brushes.White, rectf);

                    lblBlobHeight.Content = rect.Height;
                    lblBlobWidth.Content  = rect.Width;

                    blobArrayIndex++;
                }

                BitmapImage indexMap_temp = ToBitmapImage(indexMap);
                g.Flush();
                // conver to managed image if it is required to display it at some point of time
                Bitmap managedImage = unmanagedImage1.ToManagedImage();

                // create filter
                Add filter = new Add(indexMap);
                // apply the filter
                Bitmap      resultImage    = filter.Apply(managedImage);
                BitmapImage GrayImage_temp = ToBitmapImage(resultImage);

                imgGray.Source = GrayImage_temp;

                stopwatch.Stop();
                lblTime.Content = stopwatch.ElapsedMilliseconds;



                lbl9var_1.Content   = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.S1);
                lbl9var_2.Content   = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.S2);
                lbl9var_3.Content   = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.S3);
                lbl9var_4.Content   = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.S4);
                lbl9var_5.Content   = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.S5);
                lbl9var_6.Content   = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.S6);
                lbl9var_7.Content   = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.S7);
                lbl9var_8.Content   = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.S8);
                lbl9var_9.Content   = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.S9);
                lbl9var_avg.Content = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.Savg);

                lblLib.Content           = "AForge";
                lblVariance.Content      = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.All);
                lblX.Content             = breadBlob1[blobPt].X;
                lblY.Content             = breadBlob1[blobPt].Y;
                lblQ1Variance.Content    = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.Q1);
                lblQ2Variance.Content    = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.Q2);
                lblQ3Variance.Content    = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.Q3);
                lblQ4Variance.Content    = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.Q4);
                lblQAverage.Content      = breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.QAverage);
                lblAllMuffinStat.Content = MuffinStatistics.StandardDeviation;


                // System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\Histogram.txt", GrayImage1Histogram_str);
                // E:\Brian\Project 3 - English Muffin Onsite Data Gathering\Data Analysis
                //System.IO.File.WriteAllLines(@"E:\Brian\Project 3 - English Muffin Onsite Data Gathering\Data Analysis\Histogram.txt", GrayImage1Histogram_str);
                bool fileExist = File.Exists("C:\\Users\\kai23\\Projects\\ABI\\EnglishMuffinVision_AForge\\Data Analysis\\Data.csv");
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\kai23\Projects\ABI\EnglishMuffinVision_AForge\Data AnalysisData.csv", true))
                {
                    if (!fileExist)
                    {
                        file.WriteLine("File Info" +
                                       "Variance All," +
                                       "Vari Q1:," +
                                       "Vari Q2:," +
                                       "Vari Q3:," +
                                       "Vari Q4:," +
                                       "Variance Average:");
                    }

                    file.WriteLine(Convert.ToString(lblFolder.Content) + "," +
                                   Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.All)) + "," +
                                   Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.Q1)) + "," +
                                   Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.Q2)) + "," +
                                   Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.Q3)) + "," +
                                   Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.Q4)) + "," +
                                   Convert.ToString(breadBlob1[blobPt].GetVariance(BreadBlob.VarianceType.QAverage)));
                }
            }
        }