Esempio n. 1
0
 public static Bitmap ToInvert(this Bitmap bitmap)
 {
     // create filter
     AForge.Imaging.Filters.Invert filter = new AForge.Imaging.Filters.Invert();
     // apply the filter
     return(filter.Apply(bitmap));
 }
        public static bool HaveLabelRF(Bitmap imagePassport)
        {
            bool haveLabel = false;

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

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

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

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

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

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

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

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

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

                    if (CompareLabel(RF3) > 70.0)
                    {
                        haveLabel = true;
                    }
                }
            }
            return(haveLabel);
        }
Esempio n. 3
0
        /// <summary>
        /// Generates the filtered Image.
        /// </summary>
        public Bitmap process(Bitmap frame)
        {
            Bitmap test = null;
            if (frame != null)
            {
                AForge.Imaging.Filters.Invert filter = new AForge.Imaging.Filters.Invert();
                // apply the filter
                test = new Bitmap(frame.Width, frame.Height, PixelFormat.Format24bppRgb);

                for (int i = 0; i < frame.Width; i++)
                {
                    for (int j = 0; j < frame.Height; j++)
                    {
                        test.SetPixel(i, j, frame.GetPixel(i, j));
                    }

                }
                /*  Graphics g = Graphics.FromImage(test);
                  g.DrawImage(frame, 0, 0);
                  g.Dispose();

                  frame = test; */
                filter.ApplyInPlace(test);
            }
            return test;
        }
Esempio n. 4
0
        /// <summary>
        /// Обработка одного сэмпла
        /// </summary>
        /// <param name="index"></param>
        private int processSample(int r, int c)
        {
            ///  Инвертируем изображение
            AForge.Imaging.Filters.Invert InvertFilter = new AForge.Imaging.Filters.Invert();
            InvertFilter.ApplyInPlace(arrayPics[r, c]);

            ///    Создаём BlobCounter, выдёргиваем самый большой кусок, масштабируем, пересечение и сохраняем
            ///    изображение в эксклюзивном использовании
            AForge.Imaging.BlobCounterBase bc = new AForge.Imaging.BlobCounter();

            bc.FilterBlobs = true;
            bc.MinWidth    = 3;
            bc.MinHeight   = 3;
            // Упорядочиваем по размеру
            bc.ObjectsOrder = AForge.Imaging.ObjectsOrder.Size;
            // Обрабатываем картинку

            bc.ProcessImage(arrayPics[r, c]);

            Rectangle[] rects = bc.GetObjectsRectangles();
            if (rects.Length == 0)
            {
                finalPics[r, c] = AForge.Imaging.UnmanagedImage.FromManagedImage(new Bitmap(100, 100));
                return(0);
            }

            // К сожалению, код с использованием подсчёта blob'ов не работает, поэтому просто высчитываем максимальное покрытие
            // для всех блобов - для нескольких цифр, к примеру, 16, можем получить две области - отдельно для 1, и отдельно для 6.
            // Строим оболочку, включающую все блоки. Решение плохое, требуется доработка
            int lx = arrayPics[r, c].Width;
            int ly = arrayPics[r, c].Height;
            int rx = 0;
            int ry = 0;

            for (int i = 0; i < rects.Length; ++i)
            {
                if (lx > rects[i].X)
                {
                    lx = rects[i].X;
                }
                if (ly > rects[i].Y)
                {
                    ly = rects[i].Y;
                }
                if (rx < rects[i].X + rects[i].Width)
                {
                    rx = rects[i].X + rects[i].Width;
                }
                if (ry < rects[i].Y + rects[i].Height)
                {
                    ry = rects[i].Y + rects[i].Height;
                }
            }

            // Обрезаем края, оставляя только центральные блобчики
            AForge.Imaging.Filters.Crop cropFilter = new AForge.Imaging.Filters.Crop(new Rectangle(lx, ly, rx - lx, ry - ly));
            finalPics[r, c] = cropFilter.Apply(arrayPics[r, c]);

            //  Масштабируем до 100x100
            AForge.Imaging.Filters.ResizeBilinear scaleFilter = new AForge.Imaging.Filters.ResizeBilinear(100, 100);
            finalPics[r, c] = scaleFilter.Apply(finalPics[r, c]);

            //  Ну и распознаём
            currentDeskState[r * 4 + c] = patternMatch(r, c);

            return(0);
        }
Esempio n. 5
0
        private void Go_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Windows.Media.Imaging.BitmapImage imagesource = imageBox.Source as System.Windows.Media.Imaging.BitmapImage;
                if (imageBox.Source == null)
                {
                    System.Windows.MessageBox.Show("Add your image to the Image 1 box!");
                    return;
                }


                System.Drawing.Bitmap image = BmpImage2Bmp(imagesource);
                System.Windows.Media.Imaging.BitmapImage final = new System.Windows.Media.Imaging.BitmapImage();

                if (!AForge.Imaging.Image.IsGrayscale(image))
                {
                    AForge.Imaging.Filters.ExtractChannel Grayer = new AForge.Imaging.Filters.ExtractChannel(0);
                    image = Grayer.Apply(image);
                }

                if (Threshold.IsChecked == true)
                {
                    imageBox.Source = null;
                    AForge.Imaging.Filters.Threshold threshold = new AForge.Imaging.Filters.Threshold((int)slider.Value);
                    threshold.ApplyInPlace(image);
                    final = Bmp2BmpImage(image);
                }
                else if (GaussianFilter.IsChecked == true)
                {
                    AForge.Imaging.Filters.GaussianBlur Gauss = new AForge.Imaging.Filters.GaussianBlur();
                    Gauss.Sigma = GaussSigma_Slide.Value;
                    Gauss.Size  = (int)GaussSize_Slide.Value;
                    AForge.Imaging.UnmanagedImage unmanagedImage = AForge.Imaging.UnmanagedImage.FromManagedImage(image);
                    AForge.Imaging.UnmanagedImage Dst            = unmanagedImage.Clone();
                    Gauss.Apply(unmanagedImage, Dst);
                    final = Bmp2BmpImage(Dst.ToManagedImage());
                }

                else if (HiPass.IsChecked == true)
                {
                    AForge.Imaging.Filters.Sharpen filter = new AForge.Imaging.Filters.Sharpen();
                    filter.ApplyInPlace(image);
                    final = Bmp2BmpImage(image);
                }

                else if (Erode.IsChecked == true)
                {
                    AForge.Imaging.Filters.Erosion filter = new AForge.Imaging.Filters.Erosion();
                    filter.ApplyInPlace(image);
                    final = Bmp2BmpImage(image);
                }

                else if (Invert.IsChecked == true)
                {
                    AForge.Imaging.Filters.Invert filter = new AForge.Imaging.Filters.Invert();
                    filter.ApplyInPlace(image);
                    final = Bmp2BmpImage(image);
                }
                else if (EdgeDetector.IsChecked == true)
                {
                    AForge.Imaging.Filters.CannyEdgeDetector filter = new AForge.Imaging.Filters.CannyEdgeDetector();
                    filter.ApplyInPlace(image);
                    final = Bmp2BmpImage(image);
                }

                else if (Median.IsChecked == true)
                {
                    AForge.Imaging.Filters.Median filter = new AForge.Imaging.Filters.Median();
                    filter.Size = (int)GaussSize_Slide.Value;
                    filter.ApplyInPlace(image);
                    final = Bmp2BmpImage(image);
                }

                else if (More.IsChecked == true)
                {
                    if (Dilate.IsSelected)
                    {
                        AForge.Imaging.Filters.Dilatation filter = new AForge.Imaging.Filters.Dilatation();
                        filter.ApplyInPlace(image);
                        final = Bmp2BmpImage(image);
                    }
                }

                imageBox.Source = final;
                TransformImage  = image;

                boxWidth  = imageBox.RenderSize.Width;
                boxHeight = imageBox.RenderSize.Height;
            }
            catch (Exception exc)
            {
                System.Windows.MessageBox.Show(exc.ToString());
            }
        }
Esempio n. 6
0
 public static Bitmap ToInvert(this Bitmap bitmap)
 {
     AForge.Imaging.Filters.Invert filter = new AForge.Imaging.Filters.Invert();
     return filter.Apply(bitmap);
 }
Esempio n. 7
0
        /// <summary>
        /// Обработка одного сэмпла
        /// </summary>
        /// <param name="index"></param>
        public static string processSample(ref Imaging.UnmanagedImage unmanaged)
        {
            string rez = "Обработка";

            ///  Инвертируем изображение
            AForge.Imaging.Filters.Invert InvertFilter = new AForge.Imaging.Filters.Invert();
            InvertFilter.ApplyInPlace(unmanaged);

            ///    Создаём BlobCounter, выдёргиваем самый большой кусок, масштабируем, пересечение и сохраняем
            ///    изображение в эксклюзивном использовании
            AForge.Imaging.BlobCounterBase bc = new AForge.Imaging.BlobCounter();

            bc.FilterBlobs = true;
            bc.MinWidth    = 10;
            bc.MinHeight   = 10;
            // Упорядочиваем по размеру
            bc.ObjectsOrder = AForge.Imaging.ObjectsOrder.Size;
            // Обрабатываем картинку

            bc.ProcessImage(unmanaged);

            Rectangle[] rects = bc.GetObjectsRectangles();
            rez = "Насчитали " + rects.Length.ToString() + " прямоугольников!";
            //if (rects.Length == 0)
            //{
            //    finalPics[r, c] = AForge.Imaging.UnmanagedImage.FromManagedImage(new Bitmap(100, 100));
            //    return 0;
            //}

            // К сожалению, код с использованием подсчёта blob'ов не работает, поэтому просто высчитываем максимальное покрытие
            // для всех блобов - для нескольких цифр, к примеру, 16, можем получить две области - отдельно для 1, и отдельно для 6.
            // Строим оболочку, включающую все блоки. Решение плохое, требуется доработка
            int lx = unmanaged.Width;
            int ly = unmanaged.Height;
            int rx = 0;
            int ry = 0;

            for (int i = 0; i < rects.Length; ++i)
            {
                if (lx > rects[i].X)
                {
                    lx = rects[i].X;
                }
                if (ly > rects[i].Y)
                {
                    ly = rects[i].Y;
                }
                if (rx < rects[i].X + rects[i].Width)
                {
                    rx = rects[i].X + rects[i].Width;
                }
                if (ry < rects[i].Y + rects[i].Height)
                {
                    ry = rects[i].Y + rects[i].Height;
                }
            }

            // Обрезаем края, оставляя только центральные блобчики
            AForge.Imaging.Filters.Crop cropFilter = new AForge.Imaging.Filters.Crop(new Rectangle(lx, ly, rx - lx, ry - ly));
            unmanaged = cropFilter.Apply(unmanaged);

            //  Масштабируем до 100x100
            AForge.Imaging.Filters.ResizeBilinear scaleFilter = new AForge.Imaging.Filters.ResizeBilinear(100, 100);
            unmanaged = scaleFilter.Apply(unmanaged);

            return(rez);
        }
Esempio n. 8
0
 public static Bitmap ToInvert(this Bitmap bitmap)
 {
     AForge.Imaging.Filters.Invert filter = new AForge.Imaging.Filters.Invert();
     return(filter.Apply(bitmap));
 }