Gather statistics about image in RGB color space.

The class is used to accumulate statistical values about images, like histogram, mean, standard deviation, etc. for each color channel in RGB color space.

The class accepts 8 bpp grayscale and 24/32 bpp color images for processing.

Sample usage:

// gather statistics ImageStatistics stat = new ImageStatistics( image ); // get red channel's histogram Histogram red = stat.Red; // check mean value of red channel if ( red.Mean > 128 ) { // do further processing }
        // Constructor
        public LevelsLinearForm(AForge.Imaging.ImageStatistics imgStat)
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
            this.imgStat = imgStat;

            if (!imgStat.IsGrayscale)
            {
                // RGB picture
                channelCombo.Items.AddRange(new object[] {"Red", "Green", "Blue"});
                channelCombo.Enabled = true;
            }
            else
            {
                // grayscale picture
                channelCombo.Items.Add("Gray");
                channelCombo.Enabled = false;
                allCheckBox.Enabled = false;
            }
            channelCombo.SelectedIndex = 0;

            filterPreview.Filter = filter;
        }
Beispiel #2
0
        // Constructor
        public LevelsLinearForm(AForge.Imaging.ImageStatistics imgStat)
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent( );

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
            this.imgStat = imgStat;

            if (!imgStat.IsGrayscale)
            {
                // RGB picture
                channelCombo.Items.AddRange(new object[] { "Red", "Green", "Blue" });
                channelCombo.Enabled = true;
            }
            else
            {
                // grayscale picture
                channelCombo.Items.Add("Gray");
                channelCombo.Enabled = false;
                allCheckBox.Enabled  = false;
            }
            channelCombo.SelectedIndex = 0;

            filterPreview.Filter = filter;
        }
        /// <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;
        }
        public override AlgorithmResult ProcessData()
        {
            byte[,] pixels = Input.Image.GetPixels();
            if (gMin == -1 || gMean == -1 || gMax == -1)
            {
                var stats = new ImageStatistics(Input.Image);
                gMin = stats.Gray.Min;
                gMax = stats.Gray.Max;
                gMean = (byte) ((gMax - gMin)/2 + gMin);
            }

            InferenceSystem system = SetupInferenceSystem((byte) gMin, (byte) gMax, (byte) gMean);
            var result = new byte[pixels.GetLength(0),pixels.GetLength(1)];

            for (int i = 0; i < pixels.GetLength(0); i++)
            {
                for (int j = 0; j < pixels.GetLength(1); j++)
                {
                    system.SetInput("LumaIn", pixels[i, j]);
                    double inferrenceResult = system.Evaluate("LumaOut");
                    result[i, j] = (byte) inferrenceResult;
                }
            }

            return new AlgorithmResult(result);
        }
 /// <summary>
 /// Convert grayscale to RGB colour space.
 /// </summary>
 /// <param name="bitmap">The bitmap.</param>
 public static Bitmap Channel(this Bitmap bitmap) {
     var imageStatistics = new ImageStatistics(bitmap);
     if (!imageStatistics.IsGrayscale) return bitmap;
     var grayscaleToRgb = new GrayscaleToRGB();
     var result = grayscaleToRgb.Apply(bitmap);
     bitmap.Dispose();
     return result;
 }
 private void GetHistogram()
 {
     ImageStatistics rgbStatistics = new ImageStatistics(_image);
     AForge.Math.Histogram h = rgbStatistics.Red;
     RedValues = h.Values;
     h = rgbStatistics.Green;
     GreenValues = h.Values;
     h = rgbStatistics.Blue;
     BlueValues = h.Values;
 }
 /// <summary>
 /// Linear correction in RGB colour space.
 /// </summary>
 /// <param name="bitmap">The bitmap.</param>
 public static Bitmap Colour(this Bitmap bitmap) {
     if ((bitmap = bitmap.Channel()) == null) return null;
     var imageStatistics = new ImageStatistics(bitmap);
     var levelsLinear = new LevelsLinear {
         InRed = imageStatistics.Red.GetRange(0.995),
         InGreen = imageStatistics.Green.GetRange(0.995),
         InBlue = imageStatistics.Blue.GetRange(0.995)
     };
     levelsLinear.ApplyInPlace(bitmap);
     return bitmap;
 }
        public static Bitmap Equalize(Bitmap image, Rectangle region)
        {
            int startX = region.Left;
            int startY = region.Top;
            int stopX = image.Width - 1;
            int stopY = image.Height - 1;
            if (startX + region.Width < image.Width)
            {
                stopX = startX + region.Width;
            }
            if (startY + region.Height < image.Height)
            {
                stopY = startX + region.Height;
            }

            int numberOfPixels = (stopX - startX) * (stopY - startY);

            Bitmap bitmap = new Bitmap(region.Width, region.Height);
            Graphics g = Graphics.FromImage(bitmap);
            g.DrawImage(image, new Rectangle(0, 0, region.Width, region.Height), region, GraphicsUnit.Pixel);
            ImageStatistics rgbStatistics = new ImageStatistics(bitmap);

            byte[] equalizedHistogramR = EqualizeHistogram(rgbStatistics.Red.Values, numberOfPixels);
            byte[] equalizedHistogramG = EqualizeHistogram(rgbStatistics.Green.Values, numberOfPixels);
            byte[] equalizedHistogramB = EqualizeHistogram(rgbStatistics.Blue.Values, numberOfPixels);

            var b = new Bitmap(image);
            BitmapData bmpData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, b.PixelFormat);
            IntPtr ptr = bmpData.Scan0;
            int stride = bmpData.Stride;

            int bytes = Math.Abs(bmpData.Stride) * b.Height;
            byte[] rgbValues = new byte[bytes];

            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);

            Parallel.For(startY, stopY, y =>
            {
                for (int x = startX; x < stopX; x++)
                {
                    int i = y * stride + x * 4;
                    rgbValues[i] = equalizedHistogramR[rgbValues[i]];
                    rgbValues[i + 1] = equalizedHistogramG[rgbValues[i + 1]];
                    rgbValues[i + 2] = equalizedHistogramB[rgbValues[i + 2]];
                }
            });

            System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);
            b.UnlockBits(bmpData);

            return b;
        }
        public override AlgorithmResult ProcessData()
        {
            var stats = new ImageStatistics(Input.Image);
            int minGray = stats.Gray.Min;
            int maxGray = stats.Gray.Max;

            byte[,] pixels = Input.Image.GetPixels();
            double[,] memberships = pixels.ApplyTransform(x => MembershipFunction(x, minGray, maxGray));
            double[,] modifiedMembership = memberships.ApplyTransform(MembershipModification);
            byte[,] newValues = modifiedMembership.ApplyTransform(Defuzzyfication).NarrowToBytes();
            Input.Measure = FuzzyMeasures.Fuzz(memberships);
            return new AlgorithmResult(newValues)
                {
                    Measure = FuzzyMeasures.Fuzz(modifiedMembership)
                };
        }
Beispiel #10
0
        // Constructor
        public ColorImageStatisticsDescription(Bitmap image)
        {
            // get image dimensions
            int width = image.Width;
            int height = image.Height;

            // lock it
            BitmapData imgData = image.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

            // gather statistics
            statRGB = new ImageStatistics(imgData);
            statHSL = new ImageStatisticsHSL(imgData);
            statYCbCr = new ImageStatisticsYCbCr(imgData);

            // unlock image
            image.UnlockBits(imgData);
        }
 /// <summary>
 /// Convert grayscale to RGB colour space.
 /// </summary>
 /// <param name="Bitmap">The bitmap.</param>
 public static Bitmap Channel(this Bitmap Bitmap)
 {
     // Initialize a new instance of the ImageStatistics class.
     ImageStatistics ImageStatistics = new ImageStatistics(Bitmap);
     // Check if the image is grayscale.
     if (ImageStatistics.IsGrayscale) {
         // Initialize a new instance of the GrayscaleToRGB class.
         GrayscaleToRGB GrayscaleToRGB = new GrayscaleToRGB();
         // Apply the filter to the image.
         Bitmap Result = GrayscaleToRGB.Apply(Bitmap);
         // Dispose of the original image.
         Bitmap.Dispose();
         // Return the result.
         return Result;
     }
     // Return the bitmap.
     return Bitmap;
 }
Beispiel #12
0
        // Set image statistics to display
        public void SetImageStatistics( ImageStatistics stats )
        {
            this.stats = stats;

            if ( stats.IsGrayscale )
            {
                activeHistogram = stats.Gray;
                histogram.Color = Color.Black;
                channelCombo.Enabled = false;

                ShowInfoForActiveHistogram( );
            }
            else
            {
                channelCombo.Enabled = true;
                channelCombo.SelectedIndex = 0;
                SelectChannel( 0 );
            }
        }
Beispiel #13
0
        private void hisVec(Bitmap videoFrame)
        {
            ImageStatistics rgbStatistics = new ImageStatistics(videoFrame);
            int[] redValues = rgbStatistics.Red.Values;
            int[] greenValues = rgbStatistics.Green.Values;
            int[] blueValues = rgbStatistics.Blue.Values;

            int[] his = new int[256];
            for (int j = 0; j < 256; j++)
            {
                his[j] = (redValues[j] + greenValues[j] + blueValues[j]) / 3;

            }

            Vechist = his[0].ToString();
            for (int i = 1; i < his.Length; i++)
            {
                Vechist = Vechist + " " + his[i].ToString();
            }
        }
Beispiel #14
0
        /// <summary>
        /// Given a Document, this heuristic attempts to determine what the background is by finding the most common rgb
        /// colors in a border around the image
        /// </summary>
        /// <param name="document">Image to be analyzed</param>
        /// <param name="border">Size of the border in percent</param>
        /// <returns>Bgr color best-guess for background color</returns>
        public static Bgr DetectBackground(Bitmap document, int border = 10)
        {
            double border2 = (double)border / 100f;
            System.Drawing.Point tl = new System.Drawing.Point((int)(border2 * document.Width), (int)(border2 * document.Height));
            System.Drawing.Point br = new System.Drawing.Point((int)(document.Width - (border2 * document.Width)), (int)(document.Height - (border2 * document.Height)));
            Rectangle rect = new Rectangle(tl.X, tl.Y, br.X - tl.X, br.Y - tl.Y);
            UnmanagedImage blackened = UnmanagedImage.FromManagedImage(document);
            AForge.Imaging.Drawing.FillRectangle(blackened, rect, Color.Black);
            Bitmap blacknew = blackened.ToManagedImage();
            AForge.Imaging.ImageStatistics stat = new ImageStatistics(blacknew);
            Histogram red = stat.RedWithoutBlack;
            Histogram green = stat.GreenWithoutBlack;
            Histogram blue = stat.BlueWithoutBlack;
            int indexR = (int)red.Median;
            int indexB = (int)blue.Median;
            int indexG = (int)green.Median;
            Emgu.CV.Image<Bgra, Byte> blackcv = new Image<Bgra, byte>(blacknew);

            return new Bgr((double)indexB, (double)indexG, (double)indexR);
        }
Beispiel #15
0
        // Gather image statistics
        public void GatherStatistics(Bitmap image)
        {
            // get statistics
            stat = (image == null) ? null : new ImageStatistics(image);

            // free
            Cursor = Cursors.Arrow;
            Capture = false;

            // clean combo
            channelCombo.Items.Clear();
            channelCombo.Enabled = false;

            if (stat != null)
            {
                if (!stat.IsGrayscale)
                {
                    // RGB picture
                    channelCombo.Items.AddRange(new object[] { "Red", "Green", "Blue" });
                    channelCombo.Enabled = true;
                }
                else
                {
                    // grayscale picture
                    channelCombo.Items.Add("Gray");
                }
                channelCombo.SelectedIndex = 0;
            }
            else
            {
                histogram.Values = null;
                meanLabel.Text = String.Empty;
                stdDevLabel.Text = String.Empty;
                medianLabel.Text = String.Empty;
                minLabel.Text = String.Empty;
                maxLabel.Text = String.Empty;
                levelLabel.Text = String.Empty;
                countLabel.Text = String.Empty;
                percentileLabel.Text = String.Empty;
            }
        }
        static bool isEmpty(Bitmap bmp)
        {
            int threshold = 80;  //threshold for number of zeroes in the histogram or number of missing grayscale values

            ImageStatistics rgbStatistics = new ImageStatistics(bmp);
            int[] redValues = rgbStatistics.Red.Values;
            int[] greenValues = rgbStatistics.Green.Values;
            int[] blueValues = rgbStatistics.Blue.Values;

            int zeroTally = 0;

            for (int i = 0; i < 256; i++)
            {
                int value = (redValues[i] + greenValues[i] + blueValues[i]) / 3;
                if (value == 0)
                    zeroTally++;
            }

            bool output = zeroTally > threshold;
            return output;
        }
 /// <summary>
 /// Linear correction in RGB colour space.
 /// </summary>
 /// <param name="Bitmap">The bitmap.</param>
 public static Bitmap Colour(this Bitmap Bitmap)
 {
     // Convert grayscale to RGB colour space.
     if ((Bitmap = Bitmap.Channel()) != null) {
         // Initialize a new instance of the LevelsLinear class.
         ImageStatistics ImageStatistics = new ImageStatistics(Bitmap);
         // Initialize a new instance of the LevelsLinear class.
         LevelsLinear LevelsLinear = new LevelsLinear {
             // Retrieve and set the range around the median for the red-channel.
             InRed = ImageStatistics.Red.GetRange(0.995),
             // Retrieve and set the range around the median for the green-channel.
             InGreen = ImageStatistics.Green.GetRange(0.995),
             // Retrieve and set the range around the median for the blue-channel.
             InBlue = ImageStatistics.Blue.GetRange(0.995)
         };
         // Apply the filter to the image.
         LevelsLinear.ApplyInPlace(Bitmap);
     }
     // Return the bitmap.
     return Bitmap;
 }
        public double GetTemperature()
        {
            var temp = 0.0;

            var image = Image.FromFile(filename);

            var grayscale = new Grayscale(0.2125, 0.7154, 0.0721);
            image = grayscale.Apply(image);

            var invert = new Invert();
            image = invert.Apply(image);

            var stats = new ImageStatistics(image);
            var levelsLinear = new LevelsLinear
            {
                InGray = stats.Gray.GetRange(2.90)
            };

            image = levelsLinear.Apply(image);

            var contrast = new ContrastStretch();
            image = contrast.Apply(image);

            var erosion = new Erosion();
            image = erosion.Apply(image);

            var blur = new GaussianBlur(2, 3);
            image = blur.Apply(image);

            var threshold = new Threshold(79);
            image = threshold.Apply(image);

            image.Save(processedFileName, System.Drawing.Imaging.ImageFormat.Jpeg);
            image.Dispose();
            var text = Recognise();

            double.TryParse(text.Replace(',', '.'), out temp);

            return temp;
        }
        private static HistogramHash GetRGBHistogram(string file)
        {
            var values = new List<int>();
            var histogramfile = Path.Combine(HitogramPath, Guid.NewGuid() + ".jpg");
            File.Copy(file, histogramfile);
            using (var bmp = new System.Drawing.Bitmap(histogramfile))
            {
                // Luminance
                var hslStatistics = new ImageStatisticsHSL(bmp);
                values.AddRange(hslStatistics.Luminance.Values.ToList());

                // RGB
                var rgbStatistics = new ImageStatistics(bmp);
                values.AddRange(rgbStatistics.Red.Values.ToList());
                values.AddRange(rgbStatistics.Green.Values.ToList());
                values.AddRange(rgbStatistics.Blue.Values.ToList());
            }

            File.Delete(histogramfile);

            return new HistogramHash(file, values);
        }
Beispiel #20
0
        void BrightNessToolStripMenuItemClick(object sender, EventArgs e)
        {
            //jika gambar kosong/null maka akan mengembalikan nilai kosong/null
            if (gambar == null)
            {
                return;
            }
            //clone variable gambar ke variable gambar2 dan menginisiasi class Rectangle
            //dan menerapkan format pixel 24bppRgb
            gambar2 = gambar.Clone(new Rectangle(0, 0, gambar.Width, gambar.Height),
                                   System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            //calculate maximum value pada gambar2
            AForge.Imaging.ImageStatistics stat = new AForge.Imaging.ImageStatistics(gambar2);
            //menginisiasi varibale max
            int max = Math.Max(Math.Max(stat.Red.Max, stat.Green.Max), stat.Blue.Max);
            //membuat filter dari inisiasi class BrightnessCorrection() pada objek brightnessCorrection
            //dengan argumen 255-max
            BrightnessCorrection brightnessCorrection = new BrightnessCorrection(255 - max);

            //menerapkan filter pada gambar2
            brightnessCorrection.ApplyInPlace(gambar2);
            pictureBox2.Image = gambar2;
        }
Beispiel #21
0
        /* Given two images it makes a histogram comparison of its color channels
         * and returns a double indicating the level of similarity.
         * The smaller the value, the more similar the images are */
        private double HistogramBitmapDifference(Bitmap image1, Bitmap image2)
        {
            ImageStatistics stats1 = new ImageStatistics(image1);
            ImageStatistics stats2 = new ImageStatistics(image2);

            double blueDiff = Math.Abs(stats1.Blue.Mean - stats2.Blue.Mean);
            double greenDiff = Math.Abs(stats1.Green.Mean - stats2.Green.Mean);
            double redDiff = Math.Abs(stats1.Red.Mean - stats2.Red.Mean);

            return ((redDiff + blueDiff + greenDiff) / 3.0d);
        }
Beispiel #22
0
        // Scan the gem Board and capture a coloured pixel from each cell
        public bool ScanGrid()
        {
            bool bMatchedAllPieces = true;
            int unmatchedCount = 0;

            Color[,] pieceColors = new Color[8, 8];
            List<double> scores = new List<double>();

            const int CellExtractionFactor = 8; // 8ths, so skip first 5 px

            int top = CellSize / CellExtractionFactor;//topOffset;
            int left = CellSize / CellExtractionFactor; //leftOffset;

            string workingPath = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), DateTime.Now.ToString("hhmm"));
            //System.IO.Directory.CreateDirectory(workingPath+"known");
            //System.IO.Directory.CreateDirectory(workingPath + "unknown");

            // Mask out board
            Bitmap bmpMask = GetBitmap("board.mask", bmpBoard.Size, bmpBoard.PixelFormat);
            if (bmpMask != null)
            {
                Subtract subFilter = new Subtract(bmpMask);

                if (subFilter != null)
                    subFilter.ApplyInPlace(bmpBoard);

                Bitmap bmpRenderedBoard;
                if (game.DebugMode)
                {
                    bmpRenderedBoard = bmpBoard.Clone(new Rectangle(0, 0, bmpBoard.Width, bmpBoard.Height), bmpBoard.PixelFormat);

                    using (Graphics g = Graphics.FromImage(bmpRenderedBoard))
                    {
                        System.Drawing.Imaging.ColorMatrix cm = new System.Drawing.Imaging.ColorMatrix();
                        cm.Matrix00 = cm.Matrix11 = cm.Matrix22 = cm.Matrix44 = 1;
                        cm.Matrix43 = 1.0F;

                        System.Drawing.Imaging.ImageAttributes ia = new System.Drawing.Imaging.ImageAttributes();

                        ia.SetColorMatrix(cm);

                        g.DrawImage(bmpBoard, new Rectangle(0, 0, bmpBoard.Width, bmpBoard.Height), 0, 0, bmpBoard.Width, bmpBoard.Height, GraphicsUnit.Pixel, ia);
                    }
                }
            }

            // Across
            for (int x = 0; x < GridSize; x++)
            {
                // Down
                for (int y = 0; y < GridSize; y++)
                {
                    int boxLeft = left + (CellSize * x);
                    int boxTop = top + (CellSize * y);

                    // Get image of current gem
                    Rectangle rect = new Rectangle(boxLeft, boxTop, CellSize - 2 * (CellSize / CellExtractionFactor), CellSize - 2 * (CellSize / CellExtractionFactor));
                    Bitmap cropped = bmpBoard.Clone(rect, bmpBoard.PixelFormat);

                    ImageStatistics stats = new ImageStatistics(cropped);

                    // Capture a colour from this gem
                    Gem PieceColor = new Gem { Name = GemColor.None, Modifiers = GemModifier.None, Color = Color.FromArgb(255, (int)stats.Red.Mean, (int)stats.Green.Mean, (int)stats.Blue.Mean) };

                    // Calculate best score
                    double bestScore = 255*3; // what should this be set to?
                    double curScore = 0;

                    foreach (Gem gem in listGemColorStats)
                    {

                        curScore = Math.Pow(gem.Color.R-stats.Red.Mean, 2)
                                 + Math.Pow(gem.Color.G-stats.Green.Mean, 2)
                                 + Math.Pow(gem.Color.B-stats.Blue.Mean, 2);

                        if (curScore < bestScore)
                        {
                            PieceColor = gem;
                            bestScore = curScore;

                        }
                    }
                    scores.Add(bestScore);
                    // Store it in the Board matrix at the correct position
                    Board[x + 3, y + 3] = PieceColor;

                    Color newColor = Color.FromArgb(255,(int)stats.Red.Mean, (int)stats.Green.Mean, (int)stats.Blue.Mean);
                    pieceColors[x, y] = newColor;

                    if (game.DebugMode)
                    {
                        if (PieceColor.Name == GemColor.None || PieceColor.Modifiers == GemModifier.Background)
                        {
                            unmatchedCount++;
                            bMatchedAllPieces = false; // Didn't match one of the pieces, break on this
                            if ((DateTime.Now - backgroundMatchTimestamp).Seconds > 5)
                            {
                                System.IO.Directory.CreateDirectory(workingPath);

                                string colorName = string.Format("_{0}_{1}_{2}_", (int)newColor.R, (int)newColor.G, (int)newColor.B);
                                string gemName = string.Format("{0}.{1}", PieceColor.Name, PieceColor.Modifiers);
                                string basePath = System.IO.Path.Combine(workingPath, gemName);

                                string thisPath = string.Format("{0}{1}.bmp", basePath, colorName);

                                cropped.Save(thisPath);
                                game.Debug(String.Format("Written out unknown gamepiece {0},{1}", x,y));

                                //System.Diagnostics.Debugger.Break();
                            }

                        }

                    }

                    if (!listGemColorStats.Contains(PieceColor))
                    {

                        //listGemColorStats.Add(PieceColor, Color.FromArgb( stats.Red.Mean, stats.Green.Mean, stats.Blue.Mean });

                    }
                    /*
                    if (debugMode)
                    {
                        if (!knownColors.Contains(PieceColor))
                        {
                            string currentFilePath = Path.Combine(workingPath, string.Format("{0}.bmp",knownColors.Count));

                            using (FileStream fs = new FileStream(currentFilePath, FileMode.Create, FileAccess.Write))
                            {
                                cropped.Save(fs, System.Drawing.Imaging.ImageFormat.Bmp);
                            }
                            debugConsole.AppendText("Saved color " + PieceColor + " to file " + currentFilePath + System.Environment.NewLine);
                            knownColors.Add(PieceColor);
                        }

                    }*/
                }
            }
            if (bMatchedAllPieces)
                backgroundMatchTimestamp = DateTime.Now;

            return bMatchedAllPieces && unmatchedCount < 3;

            // Build known averages

            //RED
            /*
             *
             *
             * 0,0 0,2 0,5 0,6
             * 1,4 1,6
             * 3,2
             * 5,2
             * 6,7
             */
            /*
            List<Tuple<int,int>> redPairs = new List<Tuple<int,int>>();

            redPairs.Add(new Tuple<int,int>(0,0));
            redPairs.Add(new Tuple<int, int>(0, 2));
            redPairs.Add(new Tuple<int, int>(0, 5));
            redPairs.Add(new Tuple<int, int>(0, 6));
            redPairs.Add(new Tuple<int, int>(1, 3));
            redPairs.Add(new Tuple<int, int>(1, 5));
            redPairs.Add(new Tuple<int, int>(3, 2));
            redPairs.Add(new Tuple<int, int>(5, 2));
            redPairs.Add(new Tuple<int,int>(6,7));

            //BLUE
            /*
             *
             *
             * 1,1 1,2
             * 2,6 2,7
             * 3,6
             * 4,7
             * 5,0 5,3 5,6
             * 6,5 6,6
             * 7,3 7,5
             */
            /*
            List<Tuple<int, int>> bluePairs = new List<Tuple<int, int>>();

            bluePairs.Add(new Tuple<int, int>(1, 1));
            bluePairs.Add(new Tuple<int, int>(1, 2));
            bluePairs.Add(new Tuple<int, int>(2, 6));
            bluePairs.Add(new Tuple<int, int>(2, 7));
            bluePairs.Add(new Tuple<int, int>(3, 6));
            bluePairs.Add(new Tuple<int, int>(4, 7));
            bluePairs.Add(new Tuple<int, int>(5, 0));
            bluePairs.Add(new Tuple<int, int>(5, 3));
            bluePairs.Add(new Tuple<int, int>(5, 6));
            bluePairs.Add(new Tuple<int, int>(6, 5));
            bluePairs.Add(new Tuple<int, int>(6, 6));
            bluePairs.Add(new Tuple<int, int>(7, 3));
            bluePairs.Add(new Tuple<int, int>(7, 5));
            */

            //GREEN
            /*
             *
             *
             * 0,7
             * 3,1 3,5
             * 4,5
             * 6,4
             * 7,1
             */
            /*
            List<Tuple<int, int>> greenPairs = new List<Tuple<int, int>>();

            greenPairs.Add(new Tuple<int, int>(0, 7));
            greenPairs.Add(new Tuple<int, int>(3, 1));
            greenPairs.Add(new Tuple<int, int>(3, 5));
            greenPairs.Add(new Tuple<int, int>(4, 5));
            greenPairs.Add(new Tuple<int, int>(6, 4));
            greenPairs.Add(new Tuple<int, int>(7, 1));

            */
            //YELLOW
            /*
             * 0,3
             * 1,7
             * 2,1 2,3 2,4
             * 4,0
             * 5,5
             * 6,2
             * 7,6 7,7
             */
            /*
            List<Tuple<int, int>> yellowPairs = new List<Tuple<int, int>>();

            yellowPairs.Add(new Tuple<int, int>(0, 3));
            yellowPairs.Add(new Tuple<int, int>(1, 7));
            yellowPairs.Add(new Tuple<int, int>(2, 1));
            yellowPairs.Add(new Tuple<int, int>(2, 3));
            yellowPairs.Add(new Tuple<int, int>(2, 4));
            yellowPairs.Add(new Tuple<int, int>(4, 0));
            yellowPairs.Add(new Tuple<int, int>(5, 5));
            yellowPairs.Add(new Tuple<int, int>(6, 2));
            yellowPairs.Add(new Tuple<int, int>(7, 6));
            yellowPairs.Add(new Tuple<int, int>(7, 7));
            */

            //PURPLE
            /*
             * 1,0 1,4 1,6
             * 2,0
             * 4,2 4,6
             * 7,0 7,2
             */
            /*
            List<Tuple<int, int>> purplePairs = new List<Tuple<int, int>>();

            purplePairs.Add(new Tuple<int, int>(1, 0));
            purplePairs.Add(new Tuple<int, int>(1, 4));
            purplePairs.Add(new Tuple<int, int>(1, 6));
            purplePairs.Add(new Tuple<int, int>(2,0));
            purplePairs.Add(new Tuple<int, int>(4, 2));
            purplePairs.Add(new Tuple<int, int>(4, 6));
            purplePairs.Add(new Tuple<int, int>(7, 0));
            purplePairs.Add(new Tuple<int, int>(7, 2));
            */
            //WHITE
            /*
             * 0,1
             * 2,2
             * 3,3 3,4
             * 6,1 6,3
             * 7,4
             */
            /*
            List<Tuple<int, int>> whitePairs = new List<Tuple<int, int>>();

            whitePairs.Add(new Tuple<int, int>(0, 1));
            whitePairs.Add(new Tuple<int, int>(2, 2));
            whitePairs.Add(new Tuple<int, int>(3, 3));
            whitePairs.Add(new Tuple<int, int>(3, 4));
            whitePairs.Add(new Tuple<int, int>(6, 1));
            whitePairs.Add(new Tuple<int, int>(6, 3));
            whitePairs.Add(new Tuple<int, int>(7, 4));
            */
            //ORANGE
            /*
             * 0,4
             * 2,5
             * 3,0 3,7
             * 4,1 4,3 4,4
             * 5,1 5,4
             * 6,0
             */
            /*
            List<Tuple<int, int>> orangePairs = new List<Tuple<int, int>>();

            orangePairs.Add(new Tuple<int, int>(0, 4));
            orangePairs.Add(new Tuple<int, int>(2, 5));
            orangePairs.Add(new Tuple<int, int>(3, 0));
            orangePairs.Add(new Tuple<int, int>(3, 7));
            orangePairs.Add(new Tuple<int, int>(4, 1));
            orangePairs.Add(new Tuple<int, int>(4, 3));
            orangePairs.Add(new Tuple<int, int>(4, 4));
            orangePairs.Add(new Tuple<int, int>(5, 1));
            orangePairs.Add(new Tuple<int, int>(5, 4));
            orangePairs.Add(new Tuple<int, int>(6, 0));

            double rMean = 0;

            double gMean = 0;

            double bMean = 0;

            foreach (Tuple<int, int> pair in purplePairs)
            {
                rMean += pieceColors[pair.Item1,pair.Item2].R;

                gMean += pieceColors[pair.Item1, pair.Item2].G;

                bMean += pieceColors[pair.Item1, pair.Item2].B;
            }

            rMean = rMean / purplePairs.Count;
            gMean = gMean / purplePairs.Count;
            bMean = bMean / purplePairs.Count;
            listGemColorStats.Clear();
            listGemColorStats.Add(Color.Blue, Color.FromArgb( rMean, gMean, bMean });
            */
        }
        /// <summary>
        /// Frame processing
        /// Color check algorithm
        /// </summary>
        /// <param name="sender">Event source</param>
        /// <param name="image">Frame to process</param>
        private void viewCam_NewFrame_ColorCheck(object sender, ref Bitmap image)
        {
            lock (this)
            {
                ImageStatistics statistics = new ImageStatistics(ObjectExtractorDialog.Value);
                BitmapData data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height),
                    ImageLockMode.ReadOnly, image.PixelFormat);
                UnmanagedImage uImage = new UnmanagedImage(data);

                // unlock image
                image.UnlockBits(data);

                // process
                Rectangle rect = ObjectDetector.TemplateColorTracking(statistics, ref uImage);

                Target.X = rect.X;
                Target.Y = rect.Y;
                Target.Width = rect.Width;
                Target.Lost = ((rect.Width < 10) || (rect.Width > 600));

                if (!rect.IsEmpty)
                {

                    // draw rectangle around derected object
                    Graphics g = Graphics.FromImage(image);

                    using (Pen pen = new Pen(Color.Red, 4))
                    {
                        g.DrawRectangle(pen, rect);
                    }
                    g.Dispose();
                }
            }
        }
Beispiel #24
0
        private void Run_Click(object sender, EventArgs e)
        {
            VideoFileReader reader = new VideoFileReader();
            // open video file
            reader.Open(textBox1.Text);
            // check some of its attributes
            //Console.WriteLine("width:  " + reader.Width);
            //Console.WriteLine("height: " + reader.Height);
            //Console.WriteLine("fps:    " + reader.FrameRate);
            //Console.WriteLine("codec:  " + reader.CodecName);
            int[][] frameRGB = new int[reader.FrameCount][];
            // read 100 video frames out of it
            for (int i = 0; i < reader.FrameCount; i++)
            {
                //int disRed = 0;
                //int disGreen = 0;
                //int disBlue = 0;
                Bitmap videoFrame = reader.ReadVideoFrame();
                // process the frame somehow
                ImageStatistics rgbStatistics = new ImageStatistics(videoFrame);
                int[] redValues = rgbStatistics.Red.Values;
                int[] greenValues = rgbStatistics.Green.Values;
                int[] blueValues = rgbStatistics.Blue.Values;

                int[] his = new int[256];
                for (int j = 0; j < 256; j++)
                {
                    his[j] = (redValues[j] + greenValues[j] + blueValues[j]) / 3;

                }
                frameRGB[i] = his;

                //Bitmap videoFrame2 = reader.ReadVideoFrame();
                //// process the frame somehow
                //ImageStatistics rgbStatistics2 = new ImageStatistics(videoFrame2);
                //int[] redValues2 = rgbStatistics2.Red.Values;
                //int[] greenValues2 = rgbStatistics2.Green.Values;
                //int[] blueValues2 = rgbStatistics2.Blue.Values;

                //for (int j = 0; j < 256; j++)
                //{
                //    disRed = disRed + Math.Abs(redValues[j] - redValues2[j]);
                //    disGreen = disGreen + Math.Abs(greenValues[j] - greenValues2[j]);
                //    disBlue = disBlue + Math.Abs(blueValues[j] - blueValues2[j]);

                //}
                //int sumdis = disRed + disGreen + disBlue;
                //สร้างตัวแปรเก็บr+G+B เอาไว้หาค่าthredshold;กำหนดเอง
                // dispose the frame when it is no longer required
                videoFrame.Dispose();
            }

            reader.Close();
            Sdis = new int[frameRGB.Length - 1];
            for (int g = 0; g < frameRGB.Length - 1; g++)
            {
                int dis = 0;
                for (int k = 0; k < 256; k++)
                {

                    dis += Math.Abs(frameRGB[g][k] - frameRGB[g + 1][k]);
                }
                Sdis[g] = dis;
            }

            this.chart1.Titles.Add("Distance");
            Series series = this.chart1.Series.Add("Distance");
            for (int ss = 0; ss < frameRGB.Length - 1; ss++)
            {

                series.Points.AddXY(ss, Sdis[ss]);
            }
        }
        public virtual void GetLiveImage()
        {
            if (_operInProgress)
            {
               // Log.Error("OperInProgress");
                return;
            }

            if (DelayedStart)
            {
                //Log.Error("Start is delayed");
                return;
            }

            if (FreezeImage)
                return;

            _operInProgress = true;
            _totalframes++;
            if ((DateTime.Now - _framestart).TotalSeconds > 0)
                Fps = (int)(_totalframes / (DateTime.Now - _framestart).TotalSeconds);
            try
            {
                LiveViewData = LiveViewManager.GetLiveViewImage(CameraDevice);
            }
            catch (Exception ex)
            {
                Log.Error("Error geting lv", ex);
                _operInProgress = false;
                return;
            }

            if (LiveViewData == null)
            {
                _operInProgress = false;
                return;
            }

            if (!LiveViewData.IsLiveViewRunning && !IsFocusStackingRunning)
            {
                DelayedStart = true;
                _restartTimerStartTime = DateTime.Now;
                _restartTimer.Start();
                _operInProgress = false;
                return;
            }

            if (LiveViewData.ImageData == null)
            {
               // Log.Error("LV image data is null !");
                _operInProgress = false;
                return;
            }

            Recording = LiveViewData.MovieIsRecording;
            try
            {
                if (LiveViewData != null && LiveViewData.ImageData != null)
                {
                    MemoryStream stream = new MemoryStream(LiveViewData.ImageData,
                        LiveViewData.
                            ImageDataPosition,
                        LiveViewData.ImageData.
                            Length -
                        LiveViewData.
                            ImageDataPosition);
                    LevelAngle = (int)LiveViewData.LevelAngleRolling;
                    SoundL = LiveViewData.SoundL;
                    SoundR = LiveViewData.SoundR;
                    PeakSoundL = LiveViewData.PeakSoundL;
                    PeakSoundR = LiveViewData.PeakSoundR;
                    HaveSoundData = LiveViewData.HaveSoundData;
                    MovieTimeRemain = decimal.Round(LiveViewData.MovieTimeRemain, 2);

                    if (NoProcessing)
                    {
                        BitmapImage bi = new BitmapImage();
                        bi.BeginInit();
                        bi.CacheOption = BitmapCacheOption.OnLoad;
                        bi.StreamSource = stream;
                        bi.EndInit();
                        bi.Freeze();
                        Bitmap = bi;
                        ServiceProvider.DeviceManager.LiveViewImage[CameraDevice] = stream.ToArray();
                        _operInProgress = false;
                        return;
                    }

                    using (var res = new Bitmap(stream))
                    {
                        Bitmap bmp = res;
                        if (PreviewTime > 0 && (DateTime.Now - _photoCapturedTime).TotalSeconds <= PreviewTime)
                        {
                            var bitmap = ServiceProvider.Settings.SelectedBitmap.DisplayImage.Clone();
                            //var dw = (double)bmp.Width / bitmap.PixelWidth;
                            //bitmap = bitmap.Resize((int)(bitmap.PixelWidth * dw), (int)(bitmap.PixelHeight * dw),
                            //    WriteableBitmapExtensions.Interpolation.NearestNeighbor);
                            // flip image only if the prview not fliped
                            if (FlipImage && !ServiceProvider.Settings.FlipPreview)
                                bitmap = bitmap.Flip(WriteableBitmapExtensions.FlipMode.Vertical);
                            bitmap.Freeze();
                            ServiceProvider.DeviceManager.LiveViewImage[CameraDevice] = SaveJpeg(bitmap);
                            Bitmap = bitmap;
                            return;
                        }
                        if (DetectMotion)
                        {
                            ProcessMotionDetection(bmp);
                        }

                        if (_totalframes % DesiredFrameRate == 0 && ShowHistogram)
                        {
                            ImageStatisticsHSL hslStatistics =
                                new ImageStatisticsHSL(bmp);
                            LuminanceHistogramPoints =
                                ConvertToPointCollection(
                                    hslStatistics.Luminance.Values);
                            ImageStatistics statistics = new ImageStatistics(bmp);
                            RedColorHistogramPoints = ConvertToPointCollection(
                                statistics.Red.Values);
                            GreenColorHistogramPoints = ConvertToPointCollection(
                                statistics.Green.Values);
                            BlueColorHistogramPoints = ConvertToPointCollection(
                                statistics.Blue.Values);
                        }

                        if (HighlightUnderExp)
                        {
                            ColorFiltering filtering = new ColorFiltering();
                            filtering.Blue = new IntRange(0, 5);
                            filtering.Red = new IntRange(0, 5);
                            filtering.Green = new IntRange(0, 5);
                            filtering.FillOutsideRange = false;
                            filtering.FillColor = new RGB(Color.Blue);
                            filtering.ApplyInPlace(bmp);
                        }

                        if (HighlightOverExp)
                        {
                            ColorFiltering filtering = new ColorFiltering();
                            filtering.Blue = new IntRange(250, 255);
                            filtering.Red = new IntRange(250, 255);
                            filtering.Green = new IntRange(250, 255);
                            filtering.FillOutsideRange = false;
                            filtering.FillColor = new RGB(Color.Red);
                            filtering.ApplyInPlace(bmp);
                        }

                        var preview = BitmapFactory.ConvertToPbgra32Format(
                            BitmapSourceConvert.ToBitmapSource(bmp));
                        DrawFocusPoint(preview, true);

                        if (Brightness != 0)
                        {
                            BrightnessCorrection filter = new BrightnessCorrection(Brightness);
                            bmp = filter.Apply(bmp);
                        }

                        Bitmap newbmp = bmp;
                        if (EdgeDetection)
                        {
                            var filter = new FiltersSequence(
                                Grayscale.CommonAlgorithms.BT709,
                                new HomogenityEdgeDetector()
                                );
                            newbmp = filter.Apply(bmp);
                        }

                        WriteableBitmap writeableBitmap;

                        if (BlackAndWhite)
                        {
                            Grayscale filter = new Grayscale(0.299, 0.587, 0.114);
                            writeableBitmap =
                                BitmapFactory.ConvertToPbgra32Format(
                                    BitmapSourceConvert.ToBitmapSource(
                                        filter.Apply(newbmp)));
                        }
                        else
                        {
                            writeableBitmap =
                                BitmapFactory.ConvertToPbgra32Format(
                                    BitmapSourceConvert.ToBitmapSource(newbmp));
                        }
                        DrawGrid(writeableBitmap);
                        switch (RotationIndex)
                        {
                            case 0:
                                Rotation = 0;
                                break;
                            case 1:
                                Rotation = 90;
                                break;
                            case 2:
                                Rotation = 180;
                                break;
                            case 3:
                                Rotation = 270;
                                break;
                            case 4:
                                Rotation = LiveViewData.Rotation;
                                break;
                        }

                        if (CameraDevice.LiveViewImageZoomRatio.Value == "All")
                        {
                            preview.Freeze();
                            Preview = preview;
                            if (ShowFocusRect)
                                DrawFocusPoint(writeableBitmap);
                        }

                        if (FlipImage)
                        {
                            writeableBitmap = writeableBitmap.Flip(WriteableBitmapExtensions.FlipMode.Vertical);
                        }
                        if (CropRatio > 0)
                        {
                            CropOffsetX = (int) ((writeableBitmap.PixelWidth/2.0)*CropRatio/100);
                            CropOffsetY = (int) ((writeableBitmap.PixelHeight/2.0)*CropRatio/100);
                            writeableBitmap = writeableBitmap.Crop(CropOffsetX, CropOffsetY,
                                writeableBitmap.PixelWidth - (2*CropOffsetX),
                                writeableBitmap.PixelHeight - (2*CropOffsetY));
                        }
                        writeableBitmap.Freeze();
                        Bitmap = writeableBitmap;

                        //if (_totalframes%DesiredWebFrameRate == 0)
                        ServiceProvider.DeviceManager.LiveViewImage[CameraDevice] = SaveJpeg(writeableBitmap);
                    }
                    stream.Close();
                }
            }
            catch (Exception exception)
            {
                Log.Error(exception);
                _operInProgress = false;
            }
            finally
            {
                _operInProgress = false;
            }
            _operInProgress = false;
        }
 private void GetAdditionalData(object o)
 {
     BitmapFile file = o as BitmapFile;
     try
     {
         if (!file.FileItem.IsRaw)
         {
             using (Bitmap bmp = new Bitmap(file.FileItem.FileName))
             {
                 // Luminance
                 ImageStatisticsHSL hslStatistics = new ImageStatisticsHSL(bmp);
                 file.LuminanceHistogramPoints = ConvertToPointCollection(hslStatistics.Luminance.Values);
                 // RGB
                 ImageStatistics rgbStatistics = new ImageStatistics(bmp);
                 file.RedColorHistogramPoints = ConvertToPointCollection(rgbStatistics.Red.Values);
                 file.GreenColorHistogramPoints = ConvertToPointCollection(rgbStatistics.Green.Values);
                 file.BlueColorHistogramPoints = ConvertToPointCollection(rgbStatistics.Blue.Values);
             }
         }
     }
     catch (Exception ex)
     {
         Log.Error(ex);
     }
 }
Beispiel #27
0
        void videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            var frame = eventArgs.Frame;

            if (isTesting)
            {
                var r = new ColorFiltering(new IntRange(250, 255), new IntRange(250, 255), new IntRange(250, 255));
                var r1 = r.Apply(frame);

                ImageStatistics is0 = new ImageStatistics(r1);
                int no = is0.PixelsCountWithoutBlack;
                Console.WriteLine(no);

                m_pictureBox.Image = r1;
                return;
            }

            var cf1 = new ColorFiltering(new IntRange(250, 255), new IntRange(250, 255), new IntRange(250, 255));
            var fi1 = cf1.Apply(frame);

            ImageStatistics imageStatistics = new ImageStatistics(fi1);
            int numOn = imageStatistics.PixelsCountWithoutBlack;
            if (numOn > 10)
            {
                rawtext += "O";
            }
            else
            {
                rawtext += "-";
            }

            var ar = GetLetters(GuessMorseCode(rawtext)).ToArray();
            if (ar.Length != 0)
            {
                decodedMessage += ar[0];
                if (previousDecodedMessageLength != decodedMessage.Length)
                {
                    foreach (var c in decodedMessage)
                    {
                        Console.Write(c);
                    }
                    Console.WriteLine();
                    previousDecodedMessageLength = decodedMessage.Length;
                }
                rawtext = string.Empty;
            }
        }
Beispiel #28
0
        private void CorrectLevels()
        {
            ImageStatistics ims = new ImageStatistics(_recogimg);

            Histogram gr = ims.Gray;
            double median = gr.Median;
            double mean = gr.Mean;
            double stdev = gr.StdDev;
            //30 170 10

            //for (int i = 30; i < 170; i += 10)
            //{
            //    this.CorrectLevel(i, (int)mean);
            //    ims = new ImageStatistics(_recogimg);
            //    gr = ims.Gray;
            //    stdev = gr.StdDev;
            //    mean = gr.Mean;
            //    if (stdev >= 65 & mean >= 220) { break; }
            //}

            BradleyLocalThresholding filter = new BradleyLocalThresholding();
            // apply the filter
            filter.ApplyInPlace(_recogimg);
        }
        // Gather image statistics
        public void GatherStatistics( Bitmap image )
        {
            // avoid calculation in the case of the same image
            if ( image != null )
            {
                if ( currentImageHash == image.GetHashCode( ) )
                    return;
                currentImageHash = image.GetHashCode( );
            }

            if ( image != null )
                System.Diagnostics.Debug.WriteLine( "=== Gathering histogram" );

            // busy
            Capture = true;
            Cursor = Cursors.WaitCursor;

            // get statistics
            stat = ( image == null ) ? null : new ImageStatistics( image );

            // free
            Cursor = Cursors.Arrow;
            Capture = false;

            // clean combo
            channelCombo.Items.Clear( );
            channelCombo.Enabled = false;

            if ( stat != null )
            {
                if ( !stat.IsGrayscale )
                {
                    // RGB picture
                    channelCombo.Items.AddRange( new object[] { "Red", "Green", "Blue" } );
                    channelCombo.Enabled = true;
                }
                else
                {
                    // grayscale picture
                    channelCombo.Items.Add( "Gray" );
                }
                channelCombo.SelectedIndex = 0;
            }
            else
            {
                histogram.Values = null;
                meanLabel.Text = String.Empty;
                stdDevLabel.Text = String.Empty;
                medianLabel.Text = String.Empty;
                minLabel.Text = String.Empty;
                maxLabel.Text = String.Empty;
                levelLabel.Text = String.Empty;
                countLabel.Text = String.Empty;
                percentileLabel.Text = String.Empty;
            }
        }
 /// <summary>
 /// Accept selection
 /// </summary>
 /// <param name="sender">Event source</param>
 /// <param name="e">Event arguments</param>
 private void btnOK_Click(object sender, RoutedEventArgs e)
 {
     if (Target != Rectangle.Empty)
     {
         Value = Source.Clone(Target, Source.PixelFormat);
         Statistics = new ImageStatistics(Value);
         DialogResult = true;
         Close();
     }
 }
 public Histogram(Bitmap b)
 {
     this.bitmap   = b;
     statistics    = new AforgeImg.ImageStatistics(this.bitmap);
     hslStatistics = new AforgeImg.ImageStatisticsHSL(this.bitmap);
 }
 public Histogram DigitHistogram()
 {
     Grayscale grayScaler = new Grayscale(0.2125, 0.7154, 0.0721);
     ImageStatistics stat = new ImageStatistics(grayScaler.Apply(new Bitmap(_digit)));
     return stat.Gray;
 }
        private void timer1_Tick(object sender, EventArgs e)
        {
            IVideoSource videoSource1 = videoSourcePlayer1.VideoSource;
            Bitmap currentVideoFrame = videoSourcePlayer1.GetCurrentVideoFrame();
            pictureBox1.Image = currentVideoFrame;

            if (currentVideoFrame != null)
            {
                Crop filter1 = new Crop(new Rectangle(1, 1, 319, 479));
                Crop filter2 = new Crop(new Rectangle(321, 1, 639, 479));
                Bitmap leftimage = filter1.Apply(currentVideoFrame);
                Bitmap rightimage = filter2.Apply(currentVideoFrame);

                // get grayscale image
                IFilter grayscaleFilter = new GrayscaleRMY();
                leftimage = grayscaleFilter.Apply(leftimage);
                rightimage = grayscaleFilter.Apply(rightimage);

                // apply threshold filter
                Threshold th = new Threshold(trackBar1.Value);
                Bitmap filteredImage1 = th.Apply(leftimage);
                pictureBox2.Image = filteredImage1;
                Bitmap filteredImage2 = th.Apply(rightimage);
                pictureBox3.Image = filteredImage2;
                label6.Text = trackBar1.Value.ToString();

                ImageStatistics lftstat = new ImageStatistics(filteredImage1);
                int lftpxlcntwthoutblck = lftstat.PixelsCountWithoutBlack;
                ImageStatistics rghtstat = new ImageStatistics(filteredImage2);
                int rghtpxlcntwthoutblck = rghtstat.PixelsCountWithoutBlack;

                int val = trackBar1.Value;

                if (((lftpxlcntwthoutblck - rghtpxlcntwthoutblck) > val) || ((rghtpxlcntwthoutblck - lftpxlcntwthoutblck) > val))
                     {
                        if ((lftpxlcntwthoutblck-rghtpxlcntwthoutblck) >val)
                            {
                                //label4.Text = "left";
                                label4.Text = "right";
                             }
                         if ((rghtpxlcntwthoutblck-lftpxlcntwthoutblck) >val)
                            {
                                //label4.Text = "right";
                                label4.Text = "left";
                            }
                     }
                else if ((lftpxlcntwthoutblck == 0) && (rghtpxlcntwthoutblck == 0))
                {
                    label4.Text = "Stop!! No  space ahead";
                }
                else    {
                    label4.Text = "Forward";

                        }

               }
        }