Median filter.

The median filter is normally used to reduce noise in an image, somewhat like the mean filter. However, it often does a better job than the mean filter of preserving useful detail in the image.

Each pixel of the original source image is replaced with the median of neighboring pixel values. The median is calculated by first sorting all the pixel values from the surrounding neighborhood into numerical order and then replacing the pixel being considered with the middle pixel value.

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

Sample usage:

// create filter Median filter = new Median( ); // apply the filter filter.ApplyInPlace( image );

Initial image:

Result image:

Inheritance: BaseUsingCopyPartialFilter
Exemplo n.º 1
1
        // ==========================================================================================================
        // Functions compatible with lists:
        // ==========================================================================================================
        // Note, that each function needs to keep the image in RGB, otherwise drawing fill fail
        // =========================================================
        private void NoiseReduction_Funct(ref Bitmap frame, int par_int, double par_d, int par_R, int par_G, int par_B)
        {
            frame = Grayscale.CommonAlgorithms.RMY.Apply(frame);	// Make gray
            switch (par_int)
            {
                case 1:
                    BilateralSmoothing Bil_filter = new BilateralSmoothing();
                    Bil_filter.KernelSize =7;
                    Bil_filter.SpatialFactor = 10;
                    Bil_filter.ColorFactor = 30;
                    Bil_filter.ColorPower = 0.5;
                    Bil_filter.ApplyInPlace(frame);
                    break;

                case 2:
                    Median M_filter = new Median();
                    M_filter.ApplyInPlace(frame);
                    break;

                case 3:
                    Mean Meanfilter = new Mean();
                    // apply the MirrFilter
                    Meanfilter.ApplyInPlace(frame);
                    break;

                default:
                    Median Median_filter = new Median();
                    Median_filter.ApplyInPlace(frame);
                    break;
            }
            GrayscaleToRGB RGBfilter = new GrayscaleToRGB();	// back to color format
            frame = RGBfilter.Apply(frame);
        }
Exemplo n.º 2
1
        private void cBFilters_SelectedIndexChanged(object sender, EventArgs e)
        {
            Bitmap pictureTransform = (Bitmap)pbChoose.Image;
                if ((string)cBFilters.SelectedItem == "HSL_Filter")
                {
                    AForge.Imaging.Filters.SaturationCorrection filter = new SaturationCorrection(0.1);
                    Bitmap newImage = filter.Apply(pictureTransform);
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = newImage;
                }

                if ((string)cBFilters.SelectedItem == "Mediana")
                {
                    AForge.Imaging.Filters.Median filter = new Median();
                    Bitmap newImage = filter.Apply(pictureTransform);
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = newImage;
                }

                /*if ((string)cBFilters.SelectedItem == "Fourier_Transformation")
                {
                 Complex[] dst = new Complex[n];

                    AForge.Math.FourierTransform filter = AForge.Math.FourierTransform.DFT();// .FromBitmap(pictureTransform);
                    Bitmap newImage = filter.Apply();
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = newImage;
                }*/

                if ((string)cBFilters.SelectedItem == "Binarization")
                {
                    pictureTransform = Grayscale.CommonAlgorithms.BT709.Apply(pictureTransform);
                    Threshold threshold = new Threshold(127);
                    threshold.ApplyInPlace(pictureTransform);
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = pictureTransform;
                }

                if ((string)cBFilters.SelectedItem == "Grayscale")
                {
                    AForge.Imaging.Filters.Grayscale filter = new AForge.Imaging.Filters.Grayscale(0.2125, 0.7154, 0.0721);
                    Bitmap newImage = filter.Apply(pictureTransform);
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = newImage;
                }

                if ((string)cBFilters.SelectedItem == "FillHoles")
                {

                    pictureTransform = Grayscale.CommonAlgorithms.BT709.Apply(pictureTransform);
                    Threshold threshold = new Threshold(127);
                    threshold.ApplyInPlace(pictureTransform);
                    AForge.Imaging.Filters.FillHoles filter = new AForge.Imaging.Filters.FillHoles();
                    filter.MaxHoleHeight = 5;
                    filter.MaxHoleWidth = 15;
                    filter.CoupledSizeFiltering = false;
                    Bitmap newImage = filter.Apply(pictureTransform);
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = newImage;
                }

                if ((string)cBFilters.SelectedItem == "Opening")
                {
                    AForge.Imaging.Filters.Opening filter = new AForge.Imaging.Filters.Opening();
                    Bitmap newImage = filter.Apply(pictureTransform);
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = newImage;
                }

                if ((string)cBFilters.SelectedItem == "Closing")
                {
                    AForge.Imaging.Filters.Closing filter = new AForge.Imaging.Filters.Closing();
                    Bitmap newImage = filter.Apply(pictureTransform);
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = newImage;
                }

                if ((string)cBFilters.SelectedItem == "Erosion")
                {
                    AForge.Imaging.Filters.Erosion filter = new AForge.Imaging.Filters.Erosion();
                    Bitmap newImage = filter.Apply(pictureTransform);
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = newImage;
                }

                if ((string)cBFilters.SelectedItem == "Dilatation")
                {
                    AForge.Imaging.Filters.Dilatation filter = new AForge.Imaging.Filters.Dilatation();
                    Bitmap newImage = filter.Apply(pictureTransform);
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = newImage;
                }

                if ((string)cBFilters.SelectedItem == "Edges")
                {
                    AForge.Imaging.Filters.Edges filter = new AForge.Imaging.Filters.Edges();
                    Bitmap newImage = filter.Apply(pictureTransform);
                    pbChoose.SizeMode = PictureBoxSizeMode.CenterImage;
                    pBNew.Image = newImage;
                }
        }
Exemplo n.º 3
0
        public Bitmap process(Bitmap bmp)
        {
            Bitmap newImage = (Bitmap)bmp.Clone();

            newImage = new AForge.Imaging.Filters.GrayscaleY().Apply(newImage);
            newImage = new AForge.Imaging.Filters.Threshold(50).Apply(newImage);
            newImage = new AForge.Imaging.Filters.Median().Apply(newImage);
            newImage = new AForge.Imaging.Filters.Median().Apply(newImage);
            newImage = new AForge.Imaging.Filters.Dilatation().Apply(newImage);
            newImage = new AForge.Imaging.Filters.Median().Apply(newImage);
            newImage = new AForge.Imaging.Filters.Erosion().Apply(newImage);
            newImage = new AForge.Imaging.Filters.Erosion().Apply(newImage);

            return(newImage);
        }
Exemplo n.º 4
0
        private WriteableBitmap FindPlate(IEnumerable<Rect> rects, WriteableBitmap image)
        {
            WriteableBitmap bestCandidate = null;
            
            foreach (var rect in rects)
            {
                var croppedImage = image.Crop(rect);
                var edgeFilter = new CannyEdgeDetector();
                var smoothFilter = new Median();
                var grayFilter = new Grayscale(0.2125, 0.7154, 0.0721);
                var blobCounter = new BlobCounter();
                var cutTop = croppedImage.PixelHeight * 0.3;

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

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

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

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

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

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

                bestCandidate = croppedImage;
            }

            return bestCandidate;
        }
Exemplo n.º 5
0
        private Bitmap GetEdgedImage(WriteableBitmap writeableBitmap)
        {
            var edgeFilter = new CannyEdgeDetector(255, 0);
            var smoothFilter = new Median();
            var grayFilter = new Grayscale(0.2125, 0.7154, 0.0721);
            var bitmap = (Bitmap)writeableBitmap;

            bitmap = grayFilter.Apply(bitmap);
            smoothFilter.ApplyInPlace(bitmap);
            edgeFilter.ApplyInPlace(bitmap);

            return bitmap;
        }
Exemplo n.º 6
0
 public static Bitmap Median(Bitmap bmp)
 {
     // create filter
     Median filter = new Median();
     // apply the filter
     filter.ApplyInPlace(bmp);
     return bmp;
 }
Exemplo n.º 7
0
 private void medianToolStripMenuItem1_Click(object sender, EventArgs e)
 {
     AForge.Imaging.Filters.Median median = new AForge.Imaging.Filters.Median();
     median.ApplyInPlace(currentImage);
     pictureBox.Image = currentImage;
 }
Exemplo n.º 8
0
 private void MedianFilterButton_Click(object sender, EventArgs e)
 {
     Bitmap bmp = (Bitmap)pictureBox1.Image;
     Median filter = new Median();
     filter.ApplyInPlace(bmp);
     SaveAction(bmp);
     pictureBox1.Refresh();
     Charts();
 }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            Threshold thresh = new Threshold(10);
            Median median = new Median(9);
            Erosion3x3 erode = new Erosion3x3();
            Dilatation3x3 dilate = new Dilatation3x3();
            GrahamConvexHull hullFinder = new GrahamConvexHull();
            ConnectedComponentsLabeling ccLabeler = new ConnectedComponentsLabeling();
            BorderFollowing contourFinder = new BorderFollowing();
            GrayscaleToRGB rgb = new GrayscaleToRGB();
            ConvexHullDefects defectFinder = new ConvexHullDefects(10);

            Bitmap img = (Bitmap)Bitmap.FromFile("hand3.jpg");

            Bitmap image = Grayscale.CommonAlgorithms.BT709.Apply(img);
            thresh.ApplyInPlace(image);
            //median.ApplyInPlace(image);
            erode.ApplyInPlace(image);
            dilate.ApplyInPlace(image);

            BlobCounter counter = new BlobCounter(image);
            counter.ObjectsOrder = ObjectsOrder.Area;

            Blob[] blobs = counter.GetObjectsInformation();

            if (blobs.Length > 0)
            {
                counter.ExtractBlobsImage(image, blobs[0], true);

                UnmanagedImage hand = blobs[0].Image;

                var contour = contourFinder.FindContour(hand);

                if (contour.Count() > 0)
                {
                    var initialHull = hullFinder.FindHull(contour);

                    var defects = defectFinder.FindDefects(contour, initialHull);

                    var filteredHull = initialHull.ClusterHullPoints().FilterLinearHullPoints();

                    var palmCenter = defects.Centroid(contour);

                    var wristPoints = filteredHull.SelectWristPoints(defects, contour);

                    Bitmap color = rgb.Apply(hand).ToManagedImage();

                    //BitmapData data = color.LockBits(new Rectangle(0, 0, color.Width, color.Height), ImageLockMode.ReadWrite, color.PixelFormat);
                    //Drawing.Polyline(data, contour, Color.Blue);
                    //Drawing.Polygon(data, filteredHull, Color.Red);
                    //color.UnlockBits(data);

                    Graphics gr = Graphics.FromImage(color);

                    gr.DrawPolygon(new Pen(Brushes.Red, 3), filteredHull.ToPtArray());
                    gr.DrawLines(new Pen(Brushes.Blue, 3), contour.ToPtArray());
                    gr.DrawEllipse(new Pen(Brushes.Red, 3), palmCenter.X - 10, palmCenter.Y - 10, 20, 20);

                    foreach (ConvexityDefect defect in defects)
                    {
                        gr.DrawEllipse(new Pen(Brushes.Green, 6), contour[defect.Point].X - 10, contour[defect.Point].Y - 10, 20, 20);
                    }

                    foreach (AForge.IntPoint pt in filteredHull)
                    {
                        gr.DrawEllipse(new Pen(Brushes.Yellow, 6), pt.X - 10, pt.Y - 10, 20, 20);
                    }

                    foreach (AForge.IntPoint pt in wristPoints)
                    {
                        gr.DrawEllipse(new Pen(Brushes.PowderBlue, 6), pt.X - 10, pt.Y - 10, 20, 20);
                    }

                    ImageBox.Show(color);
                }
            }
        }
Exemplo n.º 10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:System.Object"/> class.
 /// </summary>
 /// <remarks></remarks>
 public TileDetector()
 {
     median = new Median();
     blobCounter = new BlobCounter();
     blobCounter.FilterBlobs = true;
     blobCounter.MinWidth = (int)Math.Ceiling(15f / scale);
     blobCounter.MinHeight = (int)Math.Ceiling(15f / scale);
     blobCounter.ObjectsOrder = ObjectsOrder.XY;
     resize = new ResizeBilinear(640, 480);
     this.filteredBoard = new Bitmap(640, 480);
     this.tileBlobs = new List<Blob>();
 }
Exemplo n.º 11
0
 /// <summary>
 /// Aforge median filtration
 /// </summary>
 /// <param name="image"></param>
 /// <param name="core">Median core size</param>
 public static Image Median(this Image image, int core)
 {
     var bitmapImage = new Bitmap(image);
     Median medianFilter = new Median(core);
     medianFilter.ApplyInPlace(bitmapImage);
     return bitmapImage;
 }
Exemplo n.º 12
0
 public Bitmap FiltroMedia(int n)
 {
     Median media = new Median(n);
     imagen = media.Apply(imagen);
     return imagen;
 }
Exemplo n.º 13
0
        public Bitmap Detect(Bitmap bitmap)
        {
            Bitmap grayscaleBitmap = Grayscale.CommonAlgorithms.BT709.Apply(bitmap);

            IFilter smoothingFilter = null;
            switch (_smoothMode)
            {
                case "None": smoothingFilter = null; break;
                case "Mean": smoothingFilter = new Mean(); break;
                case "Median": smoothingFilter = new Median(); break;
                case "Conservative": smoothingFilter = new ConservativeSmoothing(); break;
                case "Adaptive": smoothingFilter = new AdaptiveSmoothing(); break;
                case "Bilateral": smoothingFilter = new BilateralSmoothing(); break;
            }
            Bitmap smoothBitmap = smoothingFilter != null ? smoothingFilter.Apply(grayscaleBitmap) : grayscaleBitmap;

            IFilter edgeFilter = null;
            switch (_edgeMode)
            {
                case "Homogenity": edgeFilter = new HomogenityEdgeDetector(); break;
                case "Difference": edgeFilter = new DifferenceEdgeDetector(); break;
                case "Sobel": edgeFilter = new SobelEdgeDetector(); break;
                case "Canny": edgeFilter = new CannyEdgeDetector(); break;
            }
            Bitmap edgeBitmap = edgeFilter != null ? edgeFilter.Apply(smoothBitmap) : smoothBitmap;

            IFilter threshholdFilter = new Threshold(_threshold);
            Bitmap thresholdBitmap = _threshold == 0 ? edgeBitmap : threshholdFilter.Apply(edgeBitmap);

            BlobCounter blobCounter = new BlobCounter();
            blobCounter.FilterBlobs = true;
            blobCounter.MinHeight = _minHeight;
            blobCounter.MinWidth = _minWidth;
            blobCounter.ProcessImage(thresholdBitmap);
            Blob[] blobs = blobCounter.GetObjectsInformation();

            Bitmap outputBitmap = new Bitmap(thresholdBitmap.Width, thresholdBitmap.Height, PixelFormat.Format24bppRgb);
            Graphics bitmapGraphics = Graphics.FromImage(outputBitmap);
            Bitmap inputBitmap = null;
            switch (_drawMode)
            {
                case "Original": inputBitmap = bitmap; break;
                case "Grayscale": inputBitmap = grayscaleBitmap; break;
                case "Smooth": inputBitmap = smoothBitmap; break;
                case "Edge": inputBitmap = edgeBitmap; break;
                case "Threshold": inputBitmap = thresholdBitmap; break;
            }
            if (inputBitmap != null)
                bitmapGraphics.DrawImage(inputBitmap, 0, 0);

            Pen nonConvexPen = new Pen(Color.Red, 2);
            Pen nonRectPen = new Pen(Color.Orange, 2);
            Pen cardPen = new Pen(Color.Blue, 2);

            SimpleShapeChecker shapeChecker = new SimpleShapeChecker();
            List<IntPoint> cardPositions = new List<IntPoint>();

            for (int i = 0; i < blobs.Length; i++)
            {
                List<IntPoint> edgePoints = blobCounter.GetBlobsEdgePoints(blobs[i]);
                List<IntPoint> corners;

                if (shapeChecker.IsConvexPolygon(edgePoints, out corners))
                {
                    PolygonSubType subType = shapeChecker.CheckPolygonSubType(corners);

                    if ((subType == PolygonSubType.Parallelogram || subType == PolygonSubType.Rectangle) && corners.Count == 4)
                    {
                        // Check if its sideways, if so rearrange the corners so it's vertical.
                        RearrangeCorners(corners);

                        // Prevent detecting the same card twice by comparing distance against other detected cards.
                        bool sameCard = false;
                        foreach (IntPoint point in cardPositions)
                        {
                            if (corners[0].DistanceTo(point) < _minDistance)
                            {
                                sameCard = true;
                                break;
                            }
                        }
                        if (sameCard)
                            continue;

                        // Hack to prevent it from detecting smaller sections of the card instead of the whole card.
                        if (GetArea(corners) < _minArea)
                            continue;

                        cardPositions.Add(corners[0]);

                        bitmapGraphics.DrawPolygon(cardPen, ToPointsArray(corners));
                    }
                    else
                    {
                        foreach (IntPoint point in edgePoints.Take(300))
                        {
                            bitmapGraphics.DrawEllipse(nonRectPen, point.X, point.Y, 1, 1);
                        }
                    }
                }
                else
                {
                    foreach (IntPoint point in edgePoints.Take(300))
                    {
                        bitmapGraphics.DrawEllipse(nonConvexPen, point.X, point.Y, 1, 1);
                    }
                }
            }

            bitmapGraphics.Dispose();
            nonConvexPen.Dispose();
            nonRectPen.Dispose();
            cardPen.Dispose();

            return outputBitmap;
        }
Exemplo n.º 14
0
 /// <summary>
 /// Used to remove nosie in an image.
 /// </summary>
 /// <param name="oriImage"></param>
 /// <returns></returns>
 public static Image RemoveNoise(Image oriImage)
 {
     Median filter = new Median();
     Image result = filter.Apply((Bitmap)oriImage);
     return result;
 }
Exemplo n.º 15
0
 /// <summary>
 /// Filter: Median Blur
 /// Subtract the medium blur (block size ~letter size) from the image
 /// </summary>
 public void SubtractMedianBlur()
 {
     var filter = new Median(); // create filter
     filter.ApplyInPlace(Image); // apply the filter
     Save("medianBlurred");
 }