OpenCvSharp – Gaussian/mean filtering, erosion and expansion, opening/closing operations (source code attached)

Table of Contents

Core knowledge:

Core functions:

CV2.Blur() mean filtering

Cv2.GaussianBlue() Gaussian filter

Cv2.GetStructuringElement() creates structuring elements for morphological operations

Cv2.Erode() corrosion

Cv2.Dilate() dilation

Cv2.MorphologyEx() Morphological operations (corrosion expansion, opening and closing operations)

Example:

Source code:


Core knowledge:

  1. Mean filter: A commonly used image smoothing method, which reduces the noise in the image by averaging the pixel values within the pixel area, thereby achieving the effect of image smoothing and making the image blurr.

  2. Dilation: Morphological operation, used to expand bright areas (areas with larger pixel values) in the image. Its principle is to slide structural elements on the image and set the pixels in the area covered by the structural elements to the maximum pixel value. Dilation operations can increase the size of bright regions, fill small holes, and connect adjacent regions.

  3. Erosion: Morphological operation used to shrink bright areas in an image while expanding dark areas (areas with smaller pixel values). The principle is to slide the structural element on the image, and set the pixels within the area covered by the structural element to the minimum pixel value. Erosion operations can remove small noises, segment connected regions, and change the shape of regions.

  4. Opening: Corrosion operation is performed first, and then dilation operation is performed. Usually used to remove small noise points.

  5. Closing: The expansion operation is performed first, and then the erosion operation is performed. Usually used to fill small cavities.

Core Function:

CV2.Blur() average filter

Cv2.Blur(Mat src, Mat dst, Size ksize, Point anchor = null, BorderTypes borderType = BorderTypes.Default);
  • src: input image.
  • dst: output image, the result of filtering operation will be stored here.
  • ksize: Kernel size, should be a positive odd number.
  • anchor: Kernel anchor point, the default is the center point.
  • borderType: Border extension method, the default is BorderTypes.Default.

Cv2.GaussianBlue() Gaussian filter

void Cv2.GaussianBlur( src, dst, Size ksize, double sigmaX, double sigmaY = 0, BorderTypes borderType = BorderTypes.Default);
  • ksize: The size of the Gaussian kernel, which must be a positive odd number. This parameter determines the degree of blurring.
  • sigmaX: Gaussian kernel standard deviation in the X direction. If set to 0, it is calculated from ksize.width.
  • sigmaY: Gaussian kernel standard deviation in the Y direction. If set to 0, same as sigmaX.
  • borderType: border filling method, the default is BorderTypes.Default.

Cv2.GetStructuringElement() creates a structural element for morphological operations

is used to create the structural elements required for dilation and corrosion operations

Mat Cv2.GetStructuringElement(MorphShapes shape, Size ksize, Point anchor = null);
  • shape: The shape of the structural element, which can be MorphShapes.Rect (rectangle), MorphShapes.Ellipse (ellipse) or MorphShapes.Cross (cross).
  • ksize: The size of the structure element, that is, the size of the matrix.
  • anchor: The anchor point of the structural element, the default is null. In most cases, there is no need to set this parameter.

Cv2.Erode() corrosion

Cv2.Erode(Mat src, Mat dst, Mat kernel, Point anchor, int iterations, BorderTypes borderType, Scalar borderValue);
  • src: input image.
  • dst: Output image, the results of the corrosion operation will be stored here.
  • kernel: Structural element that defines the shape and size of corrosion.
  • anchor: The anchor point of the structural element, the default is the center point.
  • iterations: The number of iterations of corrosion, the default is 1.
  • borderType: border expansion method, the default is BorderTypes.Default.
  • borderValue: The value filled when the border is extended, the default is the default border value.

Cv2.Dilate() dilation

Cv2.Dilate(Mat src, Mat dst, Mat kernel, Point anchor = null, int iterations = 1, BorderTypes borderType = BorderTypes.Default, Scalar borderValue = default)

Parameters are the same as corrosion

Cv2.MorphologyEx() Morphology operation (corrosion expansion, opening and closing operation)

Cv2.MorphologyEx(Mat src, Mat dst, MorphTypes op, Mat kernel, OpenCvSharp.Point anchor = null, int iterations = 1, BorderTypes borderType = BorderTypes.Constant, Scalar borderValue = default);
  • src: input image, the source image for morphological operations.
  • dst: output image, the result of morphological operation will be saved here.
  • op: The type of morphological operation, the optional option is MorphTypes enumeration, including MorphTypes.Erode, MorphTypes.Dilate, MorphTypes.Open (open operation), MorphTypes.Close (close operation), etc.
  • kernel: Structural element that defines the shape and size of morphological operations.
  • anchor: The anchor point position of the structural element, the default is null, which means the anchor point of the structural element is at the center.
  • iterations: The number of iterations of the morphological operation, indicating the number of times to apply the operation, and the default is 1.

Example:

Mat srcImage = Cv2.ImRead("input.jpg", ImreadModes.Grayscale);
Mat element = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(3, 3));

// Corrosion
Mat erodedImage = new Mat();
Cv2. Erode(srcImage, erodedImage, element);

//expand
Mat dilatedImage = new Mat();
Cv2. Dilate(srcImage, dilatedImage, element);

// Open operation
Cv2.MorphologyEx(srcImage, dstImageOpen, MorphTypes.Open, element);

// closing operation
Cv2.MorphologyEx(srcImage, dstImageClose, MorphTypes.Close, element);

Source Code:

1. Create a form program, four buttons

2. Source code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System. Drawing;
using System.Linq;
using System.Text;
using System. Threading. Tasks;
using System.Windows.Forms;
using OpenCvSharp;
using OpenCvSharp. Extensions;

namespace image blur_mean filtering
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private Mat srcImage; // Member variable is used to share image in different methods

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                //Select image file
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "Image Files(*.jpg;*.png;*.bmp;*)|*.jpg;*.png;*.bmp;";
                if (openFileDialog. ShowDialog() != DialogResult. OK)
                    return;

                string imagePath = openFileDialog. FileName;

                // read image
                 srcImage = Cv2. ImRead(imagePath);
                //Show original image
                Cv2.NamedWindow("Original image", WindowFlags.Normal);
                Cv2.ResizeWindow("Original image", 800, 640);
                Cv2.ImShow("Original Image", srcImage);
            }
            catch (OpenCvSharp. OpenCVException ex)
            {
                //handle exception
                MessageBox.Show("An error occurred in image processing" + ex.Message);
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (srcImage == null)
            {
                MessageBox.Show("Please load the image first!");
                return;
            }
            //mean filter
            Mat dstImage = new Mat();
            Cv2.Blur(srcImage, dstImage, new OpenCvSharp.Size() { Width = 7, Height = 7 });

            Cv2.ImShow("mean filtering effect", dstImage);
            Cv2.WaitKey();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (srcImage == null)
            {
                MessageBox.Show("Please load the image first!");
                return;
            }

            // Perform corrosion operations
            Mat element = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size() { Width = 15, Height = 15 });
            Mat dstImage2 = new Mat();
            Cv2.Erode(srcImage, dstImage2, element);
      
          
            Cv2.ImShow("Corrosion Effect", dstImage2);
            Cv2.WaitKey();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (srcImage == null)
            {
                MessageBox.Show("Please load the image first!");
                return;
            }

            // Perform expansion operation
            Mat element = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size() { Width = 15, Height = 15 });
            Mat dstImage3 = new Mat();
            Cv2.Dilate(srcImage, dstImage3, element);

            Cv2.ImShow("expansion effect", dstImage3);
            Cv2.WaitKey();
        }
    }
    
}