/// <summary>
        /// 根据图片的纵横灰度情况截取图片
        /// 使用Aforge类库
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public static Rectangle GetByGrayPoint(Bitmap image)
        {
            //灰度化
            Grayscale g = new Grayscale(0.2125, 0.7154, 0.0721);
            // apply the filter
            var grayImg = g.Apply(image);
            //二值化
            var threshold = new Threshold();

            threshold.ThresholdValue = 80;
            var thresholdImage = threshold.Apply(grayImg);

            //找出纵横灰度值
            HorizontalIntensityStatistics hs = new HorizontalIntensityStatistics(thresholdImage);
            VerticalIntensityStatistics   vs = new VerticalIntensityStatistics(thresholdImage);
            var vThreshold = (image.Height / 4) * 255;
            var hThreshold = (image.Width / 4) * 255;
            var hGrays     = hs.Gray.Values.ToList();
            var vGrays     = vs.Gray.Values.ToList();
            var hmin       = FindPaperBorder(hGrays, true, hThreshold, 0);
            var hmax       = FindPaperBorder(hGrays, false, hThreshold, 0);
            var vmin       = FindPaperBorder(vGrays, true, vThreshold, 0);;
            var vmax       = FindPaperBorder(vGrays, false, vThreshold, 0);

            return(new Rectangle(hmin, vmin, hmax - hmin, vmax - vmin));
        }
        /// <summary>
        /// Build the Histogram for Supplied Image
        /// </summary>
        /// <param name="image">
        /// String: Path to image that histogram is to be created out of
        /// </param>
        public void DoHistogram(string image)
        {
            CurrentImage = image;               // Used for re-generating the histogram
            bool    IsGrayScale         = AForge.Imaging.Image.IsGrayscale(new Bitmap(image));
            dynamic IntensityStatistics = null; // Use dynamic (a little like var) to assign this variable which maybe of different types.

            swHistogram.Reset();
            swHistogram.Start();
            histogramStatus("Creating Histogram");

            AForge.Math.Histogram grayhist;
            AForge.Math.Histogram Redhist;
            AForge.Math.Histogram Greenhist;
            AForge.Math.Histogram Bluehist;
            // collect statistics
            //NOTE: We have to use the braces on these statements see: http://stackoverflow.com/questions/2496589/variable-declarations-following-if-statements
            if (IsHorizontalIntensity)
            {
                histogramStatus("Using HorizontalIntensityStatistics");
                IntensityStatistics = new HorizontalIntensityStatistics(new Bitmap(image));
            }
            else
            {
                histogramStatus("Using VerticalIntensityStatistics");
                IntensityStatistics = new VerticalIntensityStatistics(new Bitmap(image));
            }

            // get gray histogram (for grayscale image)
            if (IsGrayScale)
            {
                grayhist = IntensityStatistics.Gray;
                //TODO: DoGrayHistogram();
                histogramStatus("Grayscale Histogram");
            }
            else
            {
                Redhist   = IntensityStatistics.Red;
                Greenhist = IntensityStatistics.Green;
                Bluehist  = IntensityStatistics.Blue;
                DoRGBHistogram(Redhist, Greenhist, Bluehist);
                histogramStatus("RGB Histogram");
            }

            swHistogram.Stop();
            histogramCompleted("Histogram built in " + swHistogram.Elapsed);
        }
示例#3
0
        private void SaveImage(Bitmap bmp)
        {
            seq++;
            var fname = $@"D:\tmp\images\{seq}.bmp";

            bmp.Save(fname);

            var s = new ImageStatistics(bmp);
            var v = new VerticalIntensityStatistics(bmp);
            var h = new HorizontalIntensityStatistics(bmp);

            File.AppendAllText(
                @"D:\tmp\images\stat.csv",
                $"{seq},"
                + $"{s.Gray.Mean},{s.Gray.StdDev},"
                + $"{v.Gray.Mean},{v.Gray.StdDev},"
                + $"{h.Gray.Mean},{h.Gray.StdDev},"
                + "\r\n");
        }
示例#4
0
        /// <summary>
        /// Gets the content.
        /// </summary>
        /// <param name="mincross">Минимальная разница яркости ячейки с кретсиком</param>
        /// <param name="maxcross">Максимальная разница яркости ячейки с кретсиком</param>
        public void GetContent(double mincross, double maxcross)
        {
            _content      = false;
            _neurocontent = CellContent.Free;

            List <double> _lrange           = new List <double>();
            BitmapData    data              = _parentimage.LockBits(_rect, ImageLockMode.ReadWrite, _parentimage.PixelFormat);
            VerticalIntensityStatistics vis = new VerticalIntensityStatistics(data);

            histogram = vis.Gray;


            HorizontalIntensityStatistics his = new HorizontalIntensityStatistics(data);
            Histogram     hhistogram          = his.Gray;
            List <double> _hrange             = new List <double>();


            _parentimage.UnlockBits(data);

            for (int i = 8; i <= 15; i++)
            {
                _lrange.Add((histogram.Values[i] + hhistogram.Values[i]) / 2);
                // _hrange.Add(hhistogram.Values[i]);
            }
            // _britnessdispertion = (1 - RecogCore.Statistics.Mean(_lrange) / histogram.Values.Max()) + (1 - RecogCore.Statistics.Mean(_hrange) / hhistogram.Values.Max());
            _britnessdispertion = 1 - RecogCore.Statistics.Mean(_lrange) / histogram.Values.Max();
            if (_britnessdispertion <= mincross)
            {
                _neurocontent = CellContent.Free; _content = false;
            }
            if (_britnessdispertion > mincross & _britnessdispertion <= maxcross)
            {
                _neurocontent = CellContent.Cross; _content = true;
            }
            if (_britnessdispertion > maxcross)
            {
                _neurocontent = CellContent.Miss; _content = false;
            }
        }
示例#5
0
        /// <summary>
        /// 开始用图像识别的办法等待上钩事件,包括了右键点击收杆
        /// 计算图片的VerticalIntensityStatistics.Mean,用过去N张图片的这个值的均值作为基准
        /// 当前图片的这个值离均值的偏差超过一个阈值,则认为事件发生
        /// </summary>
        private void WaitForFish()
        {
            ShowStatus("等待鱼儿上钩……");

            // 保存过去N个值
            const int N     = 100;
            var       queue = new Queue <double>(N * 2);

            // 不停的截图,比较指标差异,超过时间则退出
            while (DateTime.Now - m_下钩时刻 < new TimeSpan(0, 0, 25))
            {
                var img = CaptureScreen();

                // 统计表明v_mean是最有效的指标
                var vs  = new VerticalIntensityStatistics(img);
                var val = vs.Gray.Mean;
                queue.Enqueue(val);
                if (queue.Count > N)
                {
                    queue.Dequeue();
                }

                // 计算均值
                var avg  = queue.Average();
                var diff = Math.Abs(val / avg - 1);

                // debug输出
                ShowDebugInfo(img, diff);

                // 阈值判断
                if (diff > m_num阈值 / 100.0)
                {
                    ShowStatus("上钩了!");
                    Win32.ClickScreen(MouseButtons.Right);
                    Thread.Sleep(3000);
                    return;
                }
            }
        }
示例#6
0
        //      gr.ResetTransform();
        //      gr.DrawRectangle(Pens.Black, 0, 0, width - 1, height - 1);


        private void DrawHistogramV(Bitmap img)
        {
            Color back_color = Color.White;

            Invert filter = new Invert();
            // apply the filter
            Bitmap inv = filter.Apply(img);

            VerticalIntensityStatistics his = new VerticalIntensityStatistics(inv);

            AForge.Math.Histogram histogram = his.Gray;

            int[] values = histogram.Values;



            Color[] Colors = new Color[] {
                Color.Red, Color.LightGreen, Color.Blue,
                Color.Pink, Color.Green, Color.LightBlue,
                Color.Orange, Color.Yellow, Color.Purple
            };



            gr2.Clear(back_color);

            // Draw the histogram.
            using (Pen thin_pen = new Pen(Color.Black, 0))
            {
                for (int i = 0; i < values.Length; i++)
                {
                    float f2 = 420F;
                    float fl = (float)values[i] / f2;
                    gr2.DrawLine(thin_pen, 0, i, fl, i);
                }
            }
        }
示例#7
0
        /// <summary>
        /// Performs hand detection calculations
        /// </summary>
        /// <param name="bmp">The camera frame to be processed</param>
        /// <returns>A bitmap representation of the detected hands</returns>
        public static Bitmap Findhands(Bitmap bmp)
        {
            Bitmap   test = new Bitmap(bmp.Width, bmp.Height);
            Graphics g    = Graphics.FromImage(test);

            for (int j = 0; j < 2; j++)
            {
                Bitmap partial = bmp.Clone(new System.Drawing.Rectangle(j * bmp.Width / 2, 0, bmp.Width / 2, bmp.Height), bmp.PixelFormat);
                HorizontalIntensityStatistics his = new HorizontalIntensityStatistics(partial);
                VerticalIntensityStatistics   vis = new VerticalIntensityStatistics(partial);
                Histogram gray  = his.Gray;
                Histogram GrayY = vis.Gray;

                double meanX;
                double meanY;

                int[] hisValues = (int[])his.Gray.Values.Clone();
                int[] visValues = (int[])vis.Gray.Values.Clone();

                List <int> lX = new List <int>();
                List <int> lY = new List <int>();

                for (int i = 0; i < hisValues.Length; i++)
                {
                    if (hisValues[i] != 0)
                    {
                        hisValues[i] = (hisValues[i] / hisValues.Max()) * 255;
                    }


                    if (hisValues[i] == 0)
                    {
                        lX.Add(i + (j * test.Width / 2));
                    }
                }
                for (int i = 0; i < visValues.Length; i++)
                {
                    if (visValues[i] != 0)
                    {
                        visValues[i] = (visValues[i] / visValues.Max()) * 255;
                    }


                    if (visValues[i] == 0)
                    {
                        lY.Add(i);
                    }
                }

                if (lX.Count != 0)
                {
                    meanX = lX.Average();
                }
                else
                {
                    meanX = 0;
                }
                if (lY.Count != 0)
                {
                    meanY = lY.Average();
                }
                else
                {
                    meanY = 0;
                }
                Rectangle r = new Rectangle((int)meanX, (int)meanY, 10, 10);
                g.DrawRectangle(new Pen(Color.Aqua), r);
            }
            return(test);
        }
示例#8
0
        /// <summary>
        /// Performs hand detection calculations within the given areas.
        /// </summary>
        /// <param name="bmp">The camera frame to be processed</param>
        /// <param name="areas">A list of rectangles in which the hand detection is to be calculated</param>
        /// <returns>A list of coordinates representing the location of each hand</returns>
        public static List <Point> GetHandLocations(Bitmap bmp, List <Rectangle> areas)
        {
            List <Point> hands = new List <Point>();

            foreach (Rectangle rect in areas)
            {
                Bitmap partial = bmp.Clone(rect, bmp.PixelFormat);
                HorizontalIntensityStatistics his = new HorizontalIntensityStatistics(partial);
                VerticalIntensityStatistics   vis = new VerticalIntensityStatistics(partial);
                Histogram gray  = his.Gray;
                Histogram GrayY = vis.Gray;

                double meanX;
                double meanY;

                int[] hisValues = (int[])his.Gray.Values.Clone();
                int[] visValues = (int[])vis.Gray.Values.Clone();

                List <int> lX = new List <int>();
                List <int> lY = new List <int>();

                for (int i = 0; i < hisValues.Length; i++)
                {
                    if (hisValues[i] != 0)
                    {
                        hisValues[i] = (hisValues[i] / hisValues.Max()) * 255;
                    }
                    if (hisValues[i] == 0)
                    {
                        lX.Add(i + rect.X);
                    }
                }
                for (int i = 0; i < visValues.Length; i++)
                {
                    if (visValues[i] != 0)
                    {
                        visValues[i] = (visValues[i] / visValues.Max()) * 255;
                    }


                    if (visValues[i] == 0)
                    {
                        lY.Add(i + rect.Y);
                    }
                }

                if (lX.Count != 0)
                {
                    meanX = lX.Average();
                }
                else
                {
                    meanX = 0;
                }
                if (lY.Count != 0)
                {
                    meanY = lY.Average();
                }
                else
                {
                    meanY = 0;
                }
                hands.Add(new Point((int)meanX, (int)meanY));
            }
            return(hands);
        }
示例#9
0
        public void test_creditcardcover()
        {
            try
            {
                const string FILE1 = @"C:\IMAGES\PB\PB742030.jpg";
                const string FILE2 = @"C:\IMAGES\PB\PB742030_done2.jpg";
                const string FILE3 = @"C:\IMAGES\PB\PB742030_done3.jpg";
                const string FILE4 = @"C:\IMAGES\PB\PB742030_done4.jpg";

                //using (var image = (Bitmap)Bitmap.FromFile(FILE1))
                //{
                //    //Invert filter = new Invert();
                //    //filter.ApplyInPlace(image);
                //    using (var img = image.ConvertToBitonal())
                //    {
                //        img.Save(FILE2, ImageFormat.Jpeg);
                //    }
                //}

                using (var image = (Bitmap)Bitmap.FromFile(FILE1))
                {
                    EuclideanColorFiltering filter = new EuclideanColorFiltering();
                    filter.CenterColor = new AForge.Imaging.RGB(Color.BlueViolet); //Pure White
                    filter.Radius      = 0;                                        //Increase this to allow off-whites
                    filter.FillColor   = new AForge.Imaging.RGB(Color.Red);        //Replacement Colour
                    filter.ApplyInPlace(image);
                }

                return;

                //To gray scale
                using (var image = (Bitmap)Bitmap.FromFile(FILE1))
                {
                    FiltersSequence seq = new FiltersSequence();
                    seq.Add(Grayscale.CommonAlgorithms.BT709); //First add  GrayScaling filter
                    seq.Add(new OtsuThreshold());              //Then add binarization(thresholding) filter
                    var img = seq.Apply(image);                // Apply filters on source image
                    img.Save(FILE2, ImageFormat.Jpeg);
                    return;
                }

                using (var image = (Bitmap)Bitmap.FromFile(FILE1))
                {
                    Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721);
                    // apply the filter
                    using (Bitmap grayImage = filter.Apply(image))
                    {
                        VerticalIntensityStatistics vis = new VerticalIntensityStatistics(grayImage);
                        // get gray histogram (for grayscale image)
                        var histogram = vis.Gray;
                        // output some histogram's information
                        System.Diagnostics.Debug.WriteLine("Mean = " + histogram.Mean);
                        System.Diagnostics.Debug.WriteLine("Min = " + histogram.Min);
                        System.Diagnostics.Debug.WriteLine("Max = " + histogram.Max);
                    }
                }



                using (var image = (Bitmap)Bitmap.FromFile(FILE2))
                {
                    VerticalIntensityStatistics vis = new VerticalIntensityStatistics(image);
                    // get gray histogram (for grayscale image)
                    var histogram = vis.Gray;
                    // output some histogram's information
                    System.Diagnostics.Debug.WriteLine("Mean = " + histogram.Mean);
                    System.Diagnostics.Debug.WriteLine("Min = " + histogram.Min);
                    System.Diagnostics.Debug.WriteLine("Max = " + histogram.Max);
                }
                //using (var image = (Bitmap)Bitmap.FromFile(FILE2))
                //{
                //    //EuclideanColorFiltering filter = new EuclideanColorFiltering();
                //    //// set center colol and radius
                //    //filter.CenterColor = new RGB(82, 26, 39);
                //    //filter.Radius = 100;
                //    //// apply the filter
                //    //filter.ApplyInPlace(image);

                //    Median filter2 = new Median();
                //    // apply the filter
                //    filter2.ApplyInPlace(image);
                //    image.Save(FILE3, ImageFormat.Jpeg);
                //}

                using (var image = (Bitmap)Bitmap.FromFile(FILE2))
                {
                    //Median filter2 = new Median();
                    //// apply the filter
                    //filter2.ApplyInPlace(image);

                    //ConservativeSmoothing filter = new ConservativeSmoothing();
                    //filter.ApplyInPlace(image);

                    //BilateralSmoothing filter = new BilateralSmoothing();
                    //filter.KernelSize = 25;
                    //filter.SpatialFactor = 10;
                    //filter.ColorFactor = 60;
                    //filter.ColorPower = 0.5;
                    //// apply the filter
                    //filter.ApplyInPlace(image);

                    ///////////////////////////////////////////

                    // create filter
                    BlobsFiltering filter3 = new BlobsFiltering();
                    // configure filter
                    //filter.CoupledSizeFiltering = true;
                    filter3.MinWidth  = 20;
                    filter3.MinHeight = 20;
                    filter3.MaxWidth  = 150;
                    filter3.MaxHeight = 150;
                    filter3.ApplyInPlace(image); //apply the filter
                    ////////////////////////////


                    //ExtractBiggestBlob filter = new ExtractBiggestBlob();
                    //// apply the filter
                    //Bitmap biggestBlobsImage = filter.Apply(image);
                    image.Save(FILE3, ImageFormat.Jpeg);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }
        // New frame received by the player
        private void videoSourcePlayer_NewFrame(object sender, ref Bitmap image)
        {
            BitmapData imageData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, image.PixelFormat);

            try
            {
                UnmanagedImage unmanagedImg = new UnmanagedImage(imageData);

                int x = (int)(unmanagedImg.Width / 3.19); // 443
                int y = (int)(unmanagedImg.Height / 2.2); // 490
                int w = (int)(unmanagedImg.Width / 2.7);  // 553
                int h = (int)(unmanagedImg.Height / 4);   // 270
                int s = (int)(unmanagedImg.Width / 10.2); // 141

                // Crop the player scroll window.  Speeds up the next couple operations
                Crop           onePlayer = new Crop(new Rectangle(x, y, w, h));
                UnmanagedImage img       = onePlayer.Apply(unmanagedImg);

                // Use a quadrilateral transformation to make the scroller a big square.
                List <IntPoint> corners = new List <IntPoint>();
                corners.Add(new IntPoint(s, 0));
                corners.Add(new IntPoint(img.Width - s, 0));;
                corners.Add(new IntPoint(img.Width, img.Height));
                corners.Add(new IntPoint(0, img.Height));

                QuadrilateralTransformation filter =
                    new QuadrilateralTransformation(corners, img.Width, img.Height);
                img = filter.Apply(img);

                // Crop the bottom half since it appears to have the best imagery
                Crop bottom = new Crop(new Rectangle(0, img.Height / 2, img.Width, img.Height / 2));
                img = bottom.Apply(img);

                UnmanagedImage grayImg = UnmanagedImage.Create(img.Width, img.Height, PixelFormat.Format8bppIndexed);
                Grayscale.CommonAlgorithms.BT709.Apply(img, grayImg);

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

                // Divide the square into 5 peices.  One for each color.
                UnmanagedImage[] colorImg = new UnmanagedImage[5];
                for (int i = 0; i < 5; i++)
                {
                    int  colorWidth  = grayImg.Width / 5;
                    int  colorHeight = grayImg.Height;
                    Crop colorCrop   = new Crop(new Rectangle(colorWidth * i, 0, colorWidth, colorHeight));
                    colorImg[i] = colorCrop.Apply(grayImg);
                }


                greenCol.Image  = colorImg[GREEN].ToManagedImage();
                redCol.Image    = colorImg[RED].ToManagedImage();
                yellowCol.Image = colorImg[YELLOW].ToManagedImage();
                blueCol.Image   = colorImg[BLUE].ToManagedImage();
                orangeCol.Image = colorImg[ORANGE].ToManagedImage();


                VerticalIntensityStatistics[] hist = new VerticalIntensityStatistics[5];

                for (int i = 0; i < 5; i++)
                {
                    hist[i] = new VerticalIntensityStatistics(colorImg[i]);
                }

                findPucks(hist);

                greenHist.Values  = hist[GREEN].Gray.Values;
                redHist.Values    = hist[RED].Gray.Values;
                yellowHist.Values = hist[YELLOW].Gray.Values;
                blueHist.Values   = hist[BLUE].Gray.Values;
                orangeHist.Values = hist[ORANGE].Gray.Values;

                pictureBox1.Image = img.ToManagedImage();
            }
            finally
            {
                image.UnlockBits(imageData);
            }
        }