/// <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;
        }
Esempio n. 2
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();
                }
        }
Esempio n. 3
0
 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;
 }
Esempio n. 4
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);
                }
            }
        }
Esempio n. 5
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;
        }
Esempio n. 6
0
        private List<Rectangle> RgrectBobberCandidate(Bitmap imgBefore, Bitmap imgAfter)
        {
            var img = XXX(imgBefore, imgAfter);
            var blobCounter = new BlobCounter();
            blobCounter.ProcessImage(img);

            return blobCounter.GetObjectsRectangles().ToList();
        }
Esempio n. 7
0
        private void ProcessImage()
        {
            m_selectedBlobs.Clear();
            pictureBox1.Controls.Clear();
            pictureBox1.Image = null;

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

            m_original = new Bitmap(txtFile.Text);

            // create grayscale filter (BT709)
            Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721);
            m_binarized = filter.Apply(m_original);

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

            // create filter
            Invert inv = new Invert();
            inv.ApplyInPlace(m_binarized);

            // create an instance of blob counter algorithm
            BlobCounter bc = new BlobCounter();
            bc.ObjectsOrder = ObjectsOrder.XY;
            bc.ProcessImage(m_binarized);
            Rectangle[] blobsRect = bc.GetObjectsRectangles();
            Dictionary<int, List<Rectangle>> orderedBlobs = ReorderBlobs(blobsRect);

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

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

            pictureBox1.Invalidate();
        }
Esempio n. 8
0
        public List<video.VideoProg.Cub> getImageColor(List<HSLFiltering> lst)
        {
            UnmanagedImage tmpCol = null;
            List<video.VideoProg.Cub> tmp = new List<video.VideoProg.Cub>();
            for(int i = 0; i < lst.Count;i++)
            {
                HSLFiltering Filter = lst[i];
                tmpCol = ImgColor.Clone();
                Filter.ApplyInPlace(tmpCol);

                // create blob counter and configure it
                BlobCounter blobCounter1 = new BlobCounter();
                blobCounter1.MinWidth = 15;                    // set minimum size of
                blobCounter1.MinHeight = 15;                   // objects we look for
                blobCounter1.FilterBlobs = true;               // filter blobs by size
                blobCounter1.ObjectsOrder = ObjectsOrder.Size; // order found object by size

                blobCounter1.ProcessImage(tmpCol);
                //Rectangle[] rects = DeleteRectInterne( blobCounter1.GetObjectsRectangles());
                Rectangle[] rects = blobCounter1.GetObjectsRectangles();
                // draw rectangle around the biggest blob
                for (int j = 0; j < rects.Length; j++)
                {
                    if (rects[j] == null)
                        break;
                    tmp.Add(new video.VideoProg.Cub(rects[j],i));
                }
            }
            ImgColor = tmpCol;
            return tmp;
        }
Esempio n. 9
0
        void VideoSourcePlayerNewFrame(object sender, ref Bitmap image)
        {
            lock (this)
            {
                Bitmap img_copy = new Bitmap(image);
                Grayscale gray_filter = new Grayscale(0.2125, 0.7154, 0.0721);
                img_copy = gray_filter.Apply(img_copy);
                Threshold thresh = new Threshold(thresh_val);
                img_copy = thresh.Apply(img_copy);
                BlobCounter 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;
                bc.ProcessImage(img_copy);
                Rectangle[] rects = bc.GetObjectsRectangles();

                Graphics g = videoSourcePlayer.CreateGraphics();
                using (Pen p = new Pen(Color.Red))
                {
                    foreach (Rectangle r in rects)
                    {
                        g.DrawRectangle(p,r);
                        g.DrawString("a",new Font("Consolas",10),Brushes.Red,r.X,r.Y);
                    }
                }
                image = img_copy;
            }
        }
Esempio n. 10
0
        private void traitementimage(ref Bitmap image)
        {

            ColorFiltering filter = new ColorFiltering();
            filter.Red = new IntRange(254, 255);
            filter.Green = new IntRange(0, 240);
            filter.Blue = new IntRange(0, 240);
            Bitmap tmp = filter.Apply(image);
            IFilter grayscale = new GrayscaleBT709();
            tmp = grayscale.Apply(tmp);
            BitmapData bitmapData = tmp.LockBits(new Rectangle(0, 0, image.Width, image.Height),
            ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
            BlobCounter blobCounter = new BlobCounter();
            blobCounter.ProcessImage(bitmapData);
            blobCounter.ObjectsOrder = ObjectsOrder.Size;
            Rectangle[] rects = blobCounter.GetObjectsRectangles();
            tmp.UnlockBits(bitmapData);
            tmp.Dispose();
            if (rects.Length != 0)
            {
                backpoint = Centre(rects[0]);
                lignes(ref image, backpoint);

            }

        }
Esempio n. 11
0
        void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            //put screen into memory
            System.Drawing.Image imgforms = (Bitmap)eventArgs.Frame.Clone();
            var ms = new MemoryStream();
            imgforms.Save(ms, ImageFormat.Bmp);
            ms.Seek(0, SeekOrigin.Begin);

            //new bitmap
            var bip = new Bitmap(ms);

            //filter
            var filter = new ColorFiltering();
            switch (_filterSwitchState)
            {
                case "filter1" :
                    filter.Red = new IntRange(0, 255);
                    filter.Green = new IntRange(0, 100);
                    filter.Blue = new IntRange(0, 100);
                    break;
                case "filter2":
                    filter.Red = new IntRange(0, 50);
                    filter.Green = new IntRange(0, 50);
                    filter.Blue = new IntRange(0, 50);
                    break;
                case "filter3":
                    filter.Red = new IntRange(175, 255);
                    filter.Green = new IntRange(130, 250);
                    filter.Blue = new IntRange(100, 200);
                    break;
                case "none":
                    filter.Red = new IntRange(0, 255);
                    filter.Green = new IntRange(0, 255);
                    filter.Blue = new IntRange(0, 255);
                    break;
            }
            filter.ApplyInPlace(bip);
            var ms2 = new MemoryStream();
            bip.Save(ms2, ImageFormat.Bmp);

            //blobs
            BlobCounterBase bc = new BlobCounter();
            bc.FilterBlobs = true;
            bc.MinWidth = 10;
            bc.MaxHeight = 400;
            bc.MaxWidth = 400;
            bc.MinHeight = 10;
            bc.ObjectsOrder = ObjectsOrder.Size;
            bc.ProcessImage(bip);
            Rectangle[] rects = bc.GetObjectsRectangles();

            var ms3 = new MemoryStream();

            if (_drawBlobState)
            {
                using (var bitmap = new Bitmap(640, 480))
                {
                    using (var canvas = Graphics.FromImage(bitmap))
                    {
                        canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        canvas.DrawImage(bip, new Rectangle(0, 0, 640, 480), new Rectangle(0, 0, 640, 480), GraphicsUnit.Pixel);
                        int i = 0;
                        foreach (Rectangle rect in rects)
                        {
                            if (_refineBlobState)
                            {
                                if (i < 4)
                                {
                                    using (var pen = new System.Drawing.Pen(System.Drawing.Color.FromArgb(255, 255, 0), 2))
                                    {
                                        canvas.DrawRectangle(pen, rect);
                                    }
                                }
                            }
                            else
                            {
                                using (var pen = new System.Drawing.Pen(System.Drawing.Color.FromArgb(255, 255, 0), 2))
                                {
                                    canvas.DrawRectangle(pen, rect);
                                }
                            }

                            i++;
                        }
                        ms3.Seek(0, SeekOrigin.Begin);
                        bitmap.Save(ms3, ImageFormat.Bmp);
                    }
                }
            }

            //read mem into bitmap for feed
            var bi = new BitmapImage();
            bi.BeginInit();
            ms2.Seek(0, SeekOrigin.Begin);
            if (_drawBlobState)
            {
                bi.StreamSource = ms3;
            }
            else
            {
                bi.StreamSource = ms2;
            }
            bi.EndInit();
            bi.Freeze();
            Dispatcher.BeginInvoke(new ThreadStart(delegate
                {
                    Viewer1.Source = bi;
                    BlobCount.Text = rects.Length.ToString();
                    Frame.Text = DateTime.Now.Ticks.ToString();
                    UpdateStatus("Pushed Frame at " + DateTime.Now.Millisecond.ToString());
                }));
        }
Esempio n. 12
0
        //functions
        public void process()
        {
            while (true)
            {
                FeatureExtracting.Notifier.WaitOne();
                foreach (Bitmap image in queue.GetConsumingEnumerable())
                {

                    BlobCounter bc = new BlobCounter();
                    bc.MinWidth = 5;
                    bc.MinHeight = 5;
                    bc.FilterBlobs = true;
                    bc.ObjectsOrder = ObjectsOrder.Size;
                    bc.ProcessImage(image);
                    Rectangle[] rects = bc.GetObjectsRectangles();
                    Rectangle biggest = new Rectangle(0, 0, 0, 0);
                    Graphics g = Graphics.FromImage(image);
                    //double ratio = 0;

            foreach (Blob blob in bc.GetObjectsInformation())
            {
             List<IntPoint> edgePoints = bc.GetBlobsEdgePoints(blob);
             List<IntPoint> top;
             List<IntPoint> bottom;
             bc.GetBlobsTopAndBottomEdges(blob, out top, out bottom);

            }

                    foreach (Rectangle r in rects)
                    {

                        biggest = rects[0];
                        g.DrawRectangle(new Pen(Color.Green, 3), r);
                    }

                    int objectCeter = 0;
                    if (biggest.Width > 70)
                    {
                        objectCeter = (((biggest.Width / 2) + biggest.X) - image.Width / 2);
                    }

                    g.DrawRectangle(new Pen(Color.Blue), biggest);

                    if (biggest.Height < 20)
                    {

                    }

                    string drawString = biggest.Height + " <-- Height    Width --> " + biggest.Width + "\n Image Center = " + objectCeter;
                    System.Drawing.Font drawFont = new System.Drawing.Font("Arial", 8);
                    System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.White);
                    float x = 10.0F;
                    float y = 10.0F;
                    System.Drawing.StringFormat drawFormat = new System.Drawing.StringFormat();
                    g.DrawString(drawString, drawFont, drawBrush, x, y, drawFormat);
                    drawFont.Dispose();
                    drawBrush.Dispose();
                    //Merge a = new Merge(image);
                    // Program.mainForm.VideoViewer.Image = a.Apply(crop.Apply(this.Camera.Image));

                    Stats a = new Stats();
                    a.blobCount = 0;
                    ActionPlanning.queue.Add(a);
                    ActionPlanning.Notifier.Set();

                    #if DEBUG
                    Program.mainForm.VideoViewer.Image = image;
                    #endif
                }
            }
        }
Esempio n. 13
0
        void FinalVideo_NewFrame2(object sender, NewFrameEventArgs eventArgs)
        {
            Icon newIcon = new Icon(@"c:\users\gregster\documents\visual studio 2012\Projects\WebCamTrack\WebCamTrack\bin\Debug\Aqua-Ball-Red-icon.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(10, 10, 10);
            filter.Radius = 20;
            filter.ApplyInPlace(video1);//aplicando o filtro
            bc.MinWidth = 12;
            bc.MinHeight = 12;
            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)
                {

                    foreach (Rectangle objectRect in rects)
                    {

                        Graphics g = Graphics.FromImage(video);//Desenhar quadrado em frente da imagem
                        Graphics i = Graphics.FromImage(video);
                        Graphics h = Graphics.FromImage(video1);
                        if (objectRect.Width < 50 && objectRect.Height < 50)
                        {
                            count = count + 1;
                        }

                        using (Pen pen = new Pen(Color.FromArgb(160, 255, 160), 5))
                        {
                            g.DrawIcon(newIcon, objectRect);
                            h.DrawRectangle(pen, objectRect);

                        }
                        string strNumber = Convert.ToString(count);
                        // Create font and brush.
                        Font drawFont = new Font("Arial", 16);
                        SolidBrush drawBrush = new SolidBrush(Color.Black);
                        // Create point for upper-left corner of drawing.
                        PointF drawPoint = new PointF(150.0F, 150.0F);
                        // Draw string to screen.
                        i.DrawString(strNumber, drawFont, drawBrush, drawPoint);

                        i.Dispose();
                        g.Dispose();
                        h.Dispose();
                    }
                }
            pictureBox1.Image = video;
            pictureBox2.Image = video1;
        }
        public void Video_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            UnmanagedImage image = UnmanagedImage.FromManagedImage((Bitmap) eventArgs.Frame.Clone());

            var extractChannel = new ExtractChannel(RGB.R);
            UnmanagedImage channel = extractChannel.Apply(image);
            //		UnmanagedImage originalRed = channel.Clone();
            if (true) {
                var threshold = new Threshold(200);
                threshold.ApplyInPlace(channel);

                ////filter to convert RGB image to 8bpp gray scale for image processing
                //IFilter gray_filter = new GrayscaleBT709();
                //gray_image = gray_filter.Apply(gray_image);

                ////thresholding a image
                //Threshold th_filter = new Threshold(color_data.threshold);
                //th_filter.ApplyInPlace(gray_image);

                //erosion filter to filter out small unwanted pixels
                Erosion3x3 erosion = new Erosion3x3();
                erosion.ApplyInPlace(channel);

                //dilation filter
                //Dilatation3x3 dilatation = new Dilatation3x3();
                //dilatation.ApplyInPlace(channel);

                //GrayscaleToRGB filter = new GrayscaleToRGB();
                //image = filter.Apply(channel);

                //ReplaceChannel replaceFilter = new ReplaceChannel(RGB.B, channel);
                //replaceFilter.ApplyInPlace(image);
            }

            BlobCounter bc = new BlobCounter();
            //arrange blobs by area
            bc.ObjectsOrder = ObjectsOrder.Area;
            bc.FilterBlobs = true;
            bc.MinHeight = minObjectSize;
            bc.MinWidth = minObjectSize;
            bc.MaxHeight = maxObjectSize;
            bc.MaxWidth = maxObjectSize;

            //process image for blobs
            bc.ProcessImage(channel);
            channel.Dispose();

            //	if (motionDetector.ProcessFrame(image) > 0.02) {
            //	for (int i = 0; i < blobCountingObjectsProcessing.ObjectRectangles.Length; i++) {
            Rectangle[] rectangles = bc.GetObjectsRectangles();
            Blob[] blobs = bc.GetObjectsInformation();
            for (int i = 0; i < bc.ObjectsCount; i++) {
                Rectangle rectangle = rectangles[i];
                int width = rectangle.Width;
                int height = rectangle.Height;

            //		if (width < maxObjectSize && height < maxObjectSize && width > minObjectSize && height > minObjectSize) {
                    Drawing.Rectangle(image, rectangle, colorList[i % colorList.Length]);

                    if (i == 0) {
                        Position = GetCenterOfMass(image, rectangle);
                        Drawing.FillRectangle(image, rectangle, Color.BlanchedAlmond);
                        Drawing.FillRectangle(image, new Rectangle((int) Position.U - dotSize, (int) Position.V - dotSize, dotSize * 3, dotSize * 3), Color.Indigo);
                    }
            //		}
            }
            //	}

            Image = image.ToManagedImage();
            //	videoForm.ImageDestination.Image = image.ToManagedImage();
        }
Esempio n. 15
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)));
                }
            }
        }
Esempio n. 16
0
        private Stats ExtractRedFeatures(Bitmap Filtered)
        {
            BlobCounter bc = new BlobCounter();
            Stats redStats = new Stats();
            bc.MinWidth = 5;
            bc.MinHeight = 5;
            bc.FilterBlobs = true;
            bc.ObjectsOrder = ObjectsOrder.Size;
            bc.ProcessImage(Filtered);
            Rectangle[] rects = bc.GetObjectsRectangles();
            Rectangle biggest = new Rectangle(0, 0, 0, 0);
            Graphics g = Graphics.FromImage(Filtered);

            if ((rects.Length > 0) && (rects[0].Height > 0))
            {
                biggest = rects[0];
                redStats.RedBlockDetected = true;
                redStats.RedBlockCenterLocation = new System.Drawing.Point(((((biggest.Width / 2) + biggest.X))), (biggest.Y + biggest.Height / 2));
                redStats.RedBlockHeight = biggest.Height;
                redStats.RedBlockWidth = biggest.Width;
                redStats.RedBlockDistance = (25.0f / biggest.Height);
                Console.WriteLine(redStats.RedBlockDistance);
            }
            else
            {
                redStats.RedBlockDetected = false;
            }

            string objectString = Math.Round((25.0f / biggest.Height), 2).ToString();
            string drawString = biggest.Height + " <-- Height    Width --> " + biggest.Width + "\n Image Center = " + (redStats.RedBlockCenterLocation.X/* - (Filtered.Width / 2)*/);
            g.DrawRectangle(new Pen(Color.Blue), biggest);
            g.DrawString(objectString, drawFont, Brushes.White, redStats.RedBlockCenterLocation.X, redStats.RedBlockCenterLocation.Y, drawFormat);
            g.DrawString(drawString, drawFont, Brushes.White, x, y, drawFormat);

            //return Filtered;
            UpdateVideo(Filtered);
            return redStats;
        }
Esempio n. 17
0
 public List<Rectangle> GetBlobRectangles(Blob blob)
 {
     BlobCounter blobCounter = new BlobCounter();
     blobCounter.ProcessImage(ImageBitmap);
     return blobCounter.GetObjectsRectangles().ToList();
 }
Esempio n. 18
0
        private Stats ExtractBlueFeatures(Bitmap Filtered)
        {
            BlobCounter bc = new BlobCounter();
            Stats blueStats = new Stats();
            bc.MinWidth = 100;
            bc.FilterBlobs = true;
            bc.ObjectsOrder = ObjectsOrder.Size;
            bc.ProcessImage(Filtered);
            Rectangle[] rects = bc.GetObjectsRectangles();
            //Graphics g = Graphics.FromImage(Filtered);
            //UpdateVideo(Filtered);

            if ((rects.Length > 0) && (rects[0].Height > 0))
            {
               // blueStats.BlueLineDetected = true;
                blueStats.BlueLineDistance = (11.0 / rects[0].Height);
            }
            else
            {
                blueStats.BlueLineDetected = false;
            }
            return blueStats;
        }
Esempio n. 19
0
        private Stats ExtractGreenFeatures(Bitmap Filtered)
        {
            BlobCounter bc = new BlobCounter();
            Stats greenStats = new Stats();
            bc.MinWidth = 15;
            bc.MinHeight = 15;
            bc.FilterBlobs = true;
            bc.ObjectsOrder = ObjectsOrder.Size;
            bc.ProcessImage(Filtered);
            Rectangle[] rects = bc.GetObjectsRectangles();
            // Graphics g = Graphics.FromImage(Filtered);

            if ((rects.Length > 0) && (rects[0].Height > 0))
            {
                greenStats.GreenBlockDetected = true;
                greenStats.GreenBlockCenterLocation = new System.Drawing.Point(((((rects[0].Width / 2) + rects[0].X))), (rects[0].Y + rects[0].Height / 2));
                greenStats.GreenBlockHeight = rects[0].Height;
                greenStats.GreenBlockWidth = rects[0].Width;
                greenStats.GreenBlockDistance = (130.0f / rects[0].Height);
            }
            else
            {
                greenStats.GreenBlockDetected = false;
            }

            //UpdateVideo(Filtered);
            return greenStats;

            // User Feedback for debug
            //string objectString = Math.Round((130.0f / biggest.Height), 2).ToString();
            //string drawString = biggest.Height + " <-- Height    Width --> " + biggest.Width + "\n Image Center = " + (greenStats.RedBlockCenterLocation.X);
            //g.DrawRectangle(new Pen(Color.Blue), biggest);
            //g.DrawString(objectString, drawFont, Brushes.White, greenStats.RedBlockCenterLocation.X, greenStats.RedBlockCenterLocation.Y, drawFormat);
            //g.DrawString(drawString, drawFont, Brushes.White, x, y, drawFormat);
            //return Filtered;
        }
        /// <summary>
        /// Get rectangles objects in the image
        /// </summary>
        /// <param name="image">Image to get the rectangles</param>
        /// <param name="minWidth">Minimum width to consider as a valid rectangle</param>
        /// <param name="minHeight">Minimum height to consider as a valid ractangle</param>
        /// <returns>Return an array with the selected rectangle</returns>
        public Rectangle[] GetObjectsCoordinates(System.Drawing.Image image, int minWidth, int minHeight)
        {
            // create grayscale filter
            GrayscaleBT709 grayscaleFilter = new GrayscaleBT709();
            // apply it to color filtered image
            Bitmap grayImage = grayscaleFilter.Apply(new Bitmap(image));

            // create blob counter
            AForge.Imaging.BlobCounter blobCounter = new AForge.Imaging.BlobCounter();
            // configure it to filter out small objects
            blobCounter.MinWidth = minWidth;
            blobCounter.MinHeight = minHeight;
            blobCounter.FilterBlobs = true;
            // set ordering - bigger objects go first
            blobCounter.ObjectsOrder = AForge.Imaging.ObjectsOrder.YX;

            // locate blobs
            blobCounter.ProcessImage(grayImage);
            Rectangle[] rects = blobCounter.GetObjectsRectangles();
            return rects;
        }
Esempio n. 21
0
        public Bitmap showMotion(Bitmap originalImage, Bitmap motionImage)
        {
            BlobCounter blobCounter = new BlobCounter();

            blobCounter.ProcessImage(motionImage);
            Rectangle[] rects = blobCounter.GetObjectsRectangles();

            Graphics g = Graphics.FromImage(originalImage);

            foreach (Rectangle rc in rects)
            {
                rat1.checkRectangleProximity(rc);
                rat2.checkRectangleProximity(rc);

            }
            rat1.computeCenter();
            rat2.computeCenter();

            rat2.compareAndChange(rat1);

            rat1.drawTracker(g);
            rat2.drawTracker(g);

            g.Dispose();

            return originalImage;
        }
Esempio n. 22
0
        public static System.Drawing.Image AforgeAutoCrop(Bitmap selectedImage,
            DetectBorderParam param)
        {
            // 一些参数的默认值
            if (param.MinObjectWidth == 0)
                param.MinObjectWidth = 500;
            if (param.MinObjectHeight == 0)
                param.MinObjectHeight = 500;

            Bitmap autoCropImage = null;
            try
            {

                autoCropImage = selectedImage;
                // create grayscale filter (BT709)
                Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721);
                Bitmap grayImage = filter.Apply(autoCropImage);
                // create instance of skew checker
                DocumentSkewChecker skewChecker = new DocumentSkewChecker();
                // get documents skew angle
                double angle = skewChecker.GetSkewAngle(grayImage);
                // create rotation filter
                RotateBilinear rotationFilter = new RotateBilinear(-angle);
                rotationFilter.FillColor = Color.White;
                // rotate image applying the filter
                Bitmap rotatedImage = rotationFilter.Apply(grayImage);
                new ContrastStretch().ApplyInPlace(rotatedImage);
                new Threshold(100).ApplyInPlace(rotatedImage);
                BlobCounter bc = new BlobCounter();
                bc.FilterBlobs = true;
                bc.MinWidth = param.MinObjectWidth; //  500;
                bc.MinHeight = param.MinObjectHeight;   // 500;
                bc.ProcessImage(rotatedImage);
                Rectangle[] rects = bc.GetObjectsRectangles();

                if (rects.Length == 0)
                {
                    System.Windows.Forms.MessageBox.Show("No rectangle found in image ");
                }
                else if (rects.Length == 1)
                {
                    autoCropImage = rotatedImage.Clone(rects[0], rotatedImage.PixelFormat);
                }
                else if (rects.Length > 1)
                {
                    // get largets rect
                    Console.WriteLine("Using largest rectangle found in image ");
                    var r2 = rects.OrderByDescending(r => r.Height * r.Width).ToList();
                    autoCropImage = rotatedImage.Clone(r2[1], rotatedImage.PixelFormat);
                }
                else
                {
                    Console.WriteLine("Huh? on image ");
                }
            }
            catch (Exception ex)
            {
                // MessageBox.Show(ex.Message);
                throw ex;
            }

            return autoCropImage;
        }
Esempio n. 23
0
        public static bool GetSkewParam(Bitmap selectedImage,
            DetectBorderParam param,
            out double angle,
            out Rectangle rect)
        {
            // 一些参数的默认值
            if (param.MinObjectWidth == 0)
                param.MinObjectWidth = 500;
            if (param.MinObjectHeight == 0)
                param.MinObjectHeight = 500;

            Bitmap autoCropImage = null;
            try
            {

                autoCropImage = selectedImage;

#if NO
                // create grayscale filter (BT709)
                Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721);
                Bitmap grayImage = filter.Apply(autoCropImage);
#endif
                Bitmap grayImage = selectedImage.Clone(new Rectangle(0, 0, selectedImage.Width, selectedImage.Height),
                System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
                // create instance of skew checker
                DocumentSkewChecker skewChecker = new DocumentSkewChecker();
                // get documents skew angle
                angle = skewChecker.GetSkewAngle(grayImage);
                // create rotation filter
                RotateBilinear rotationFilter = new RotateBilinear(-angle);
                rotationFilter.FillColor = Color.Black; // .White;
                rotationFilter.KeepSize = true;
                // rotate image applying the filter
                Bitmap rotatedImage = rotationFilter.Apply(grayImage);
                new ContrastStretch().ApplyInPlace(rotatedImage);
                new Threshold(100).ApplyInPlace(rotatedImage);
                BlobCounter bc = new BlobCounter();
                bc.FilterBlobs = true;
                bc.MinWidth = param.MinObjectWidth; //  500;
                bc.MinHeight = param.MinObjectHeight;   // 500;
#if NO
                bc.MinWidth = 500;// grayImage.Width / 10;  // 500
                bc.MinHeight = 500;// grayImage.Height / 10; // 500
#endif
                bc.ProcessImage(rotatedImage);

                Rectangle[] rects = bc.GetObjectsRectangles();

                if (rects.Length == 0)
                {
                    // System.Windows.Forms.MessageBox.Show("No rectangle found in image ");
                    rect = new Rectangle(0, 0, 0, 0);
                    return false;
                }
                else if (rects.Length == 1)
                {
                    rect = rects[0];
                    // autoCropImage = rotatedImage.Clone(rects[0], rotatedImage.PixelFormat);
                }
                else if (rects.Length > 1)
                {
                    // TODO: 应该把这些矩形合并在一起
                    Rectangle first = new Rectangle(0, 0, 0, 0);
                    int i = 0;
                    foreach (Rectangle one in rects)
                    {
                        Debug.WriteLine("one=" + one.ToString());
                        if (i == 0)
                            first = one;
                        else
                            first = Merge(first, one);
                        i++;
                    }
                    rect = first;
                    Debug.WriteLine("result=" + rect.ToString());
#if NO

                    // get largets rect
                    Console.WriteLine("Using largest rectangle found in image ");
                    var r2 = rects.OrderByDescending(r => r.Height * r.Width).ToList();
                    rect = r2[1];
                    // autoCropImage = rotatedImage.Clone(r2[1], rotatedImage.PixelFormat);
#endif
                }
                else
                {
                    // Console.WriteLine("Huh? on image ");
                    rect = new Rectangle(0, 0, 0, 0);
                    return false;
                }

#if NO
                Blob[] blobs = bc.GetObjectsInformation();
                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<Point> Points = new List<Point>();
                            foreach (var point in cornerPoints)
                            {
                                Points.Add(new Point(point.X, point.Y));
                            }

                            Graphics g = Graphics.FromImage(image);
                            g.DrawPolygon(new Pen(Color.Red, 5.0f), Points.ToArray());

                            image.Save("result.png");
                        }
                    }
                }
#endif

            }
            catch (Exception ex)
            {
                // MessageBox.Show(ex.Message);
                throw ex;
            }
            finally
            {
                if (autoCropImage != null)
                    autoCropImage.Dispose();
            }
            return true;
        }
Esempio n. 24
0
        Bitmap denoise(Bitmap bmp, Size size)
        {
            Bitmap ivbmp = bmp.Clone() as Bitmap;
            Invert iv = new Invert();
            iv.ApplyInPlace(ivbmp);

            BlobCounter bc = new BlobCounter();
            bc.FilterBlobs = true;
            bc.MinWidth = bc.MinHeight = 0;
            bc.MaxWidth = size.Width;
            bc.MaxHeight = size.Height;
            bc.ProcessImage(ivbmp);

            Rectangle[] rects = bc.GetObjectsRectangles();

            Bitmap tmp = new Bitmap(bmp);

            using (Graphics g = Graphics.FromImage(tmp))
                //g.DrawRectangles(Pens.Red, rects);
                if (rects.Length > 0)
                    g.FillRectangles(Brushes.White, rects);

            //iv.ApplyInPlace(tmp);

            return tmp;
        }
Esempio n. 25
-1
        private void AnaliseMap(Bitmap mapImage)
        {
            mapData.Clear();
            ColorFiltering filter = new ColorFiltering();
            Trace.WriteLine("Analysing color map " + mapLocation + "...");

            foreach (String action in colorMap.Actions)
            {
                Color actionColor = colorMap.GetColorFor(action);

                filter.Red = new IntRange(actionColor.R, actionColor.R);
                filter.Green = new IntRange(actionColor.G, actionColor.G);
                filter.Blue = new IntRange(actionColor.B, actionColor.B);

                using (Bitmap colorFilteredMapImage = filter.Apply(mapImage))
                {
                    // Once we have isolated the action color on the map image
                    // we need to find the biggest rectangle left in the map (as there could be noise)

                    BlobCounter bc = new BlobCounter();
                    bc.ProcessImage(colorFilteredMapImage);
                    Rectangle[] rects = bc.GetObjectsRectangles();
                    if (rects.Count<Rectangle>() == 0) Trace.WriteLine("Warning: No rectangles were found for " + actionColor.ToString());

                    Rectangle biggestRect = Rectangle.Empty;
                    foreach (Rectangle rect in rects)
                    {
                        // Compare areas
                        if (rect.Width * rect.Height > biggestRect.Width * biggestRect.Height)
                        {
                            biggestRect = rect;
                        }
                    }

                    // Did we find a rectangle?
                    if (!biggestRect.Equals(Rectangle.Empty) && (biggestRect.Width * biggestRect.Height > MIN_AREA_THRESHOLD))
                    {
                        Trace.WriteLine("Found rectangle for " + action + ": " + biggestRect.ToString());
                        mapData[action] = biggestRect;
                    }
                }
            }
        }
Esempio n. 26
-1
        /// <summary>
        /// Based off www.codeproject.com/Articles/10248/Motion-Detection-Algorithms
        /// </summary>
        /// <param name="thresholdImage"></param>
        /// <returns></returns>
        private List<Rectangle> GetLocationRectangles(Bitmap thresholdImage)
        {
            int size = thresholdImage.Size.Width / 20;

            BlobCounter blobCounter = new BlobCounter();

            blobCounter.ProcessImage(thresholdImage);
            Rectangle[] rects = blobCounter.GetObjectsRectangles();

            List<Rectangle> largeBlobRects = new List<Rectangle>();

            foreach (Rectangle rc in rects)
            {
                if ((rc.Width < size) && (rc.Height < size*2.5)) continue;

                largeBlobRects.Add(rc);
            }

            return largeBlobRects.OrderBy(x => x.Height * x.Width).ToList();
        }