Erode Images and Videos

Erosion is a fundamental morphological operation in image processing. As the name implies, this operation erodes foreground pixels in an image at their boundaries. After this erosion operation is performed, objects in an image becomes smaller where as the holes within the object (if any) becomes larger.

In this technique, each pixel value of the resultant image is calculated as the minimum value of the neighborhood of the pixel defined by the kernel. For color images, each color plane is processed independently.

3 x 3 kernel used in the erosion operation

3 x 3 kernel for erosion operation
3 x 3 kernel for erosion operation



Following image shows how to erode an image with the above 3 x 3 kernel. In the same way you can erode an image with 5 x 5, 7 x 7 and etc kernels.
Erode Image with 3 x 3 Kernel


Erode image with OpenCV


OpenCV has an in-built function to erode an image specifying the kernel size. Here is a simple program demonstrating how to erode an image with a 3 x 3 and 5 x 5 kernel with OpenCV.

//Uncomment the following line if you are compiling this code in Visual Studio
//#include "stdafx.h"

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    // Read the image file
    Mat image = imread("D:/My OpenCV Website/Lotus.jpeg");

    // Check for failure
    if (image.empty())
    {
        cout << "Could not open or find the image" << endl;
        cin.get(); //wait for any key press
        return -1;
    }

    //Erode the image with 3x3 kernel
    Mat image_eroded_with_3x3_kernel;
    erode(image, image_eroded_with_3x3_kernel, getStructuringElement(MORPH_RECT, Size(3, 3)));

    //Erode the image with 5x5 kernel
    Mat image_eroded_with_5x5_kernel;
    erode(image, image_eroded_with_5x5_kernel, getStructuringElement(MORPH_RECT, Size(5, 5)));

    //Define names of the windows
    String window_name = "Lotus";
    String window_name_eroded_with_3x3_kernel = "Lotus eroded with 3 x 3 kernel";
    String window_name_eroded_with_5x5_kernel = "Lotus eroded with 5 x 5 kernel";

    // Create windows with above names
    namedWindow(window_name);
    namedWindow(window_name_eroded_with_3x3_kernel);
    namedWindow(window_name_eroded_with_5x5_kernel);

    // Show our images inside the created windows.
    imshow(window_name, image);
    imshow(window_name_eroded_with_3x3_kernel, image_eroded_with_3x3_kernel);
    imshow(window_name_eroded_with_5x5_kernel, image_eroded_with_5x5_kernel);

    waitKey(0); // Wait for any keystroke in the window

    destroyAllWindows(); //destroy all opened windows

    return 0;
}


Copy and paste the above code snippet into your IDE and run it. Please note that you have to replace "D:/My OpenCV Website/Lotus.jpeg" in the code with a valid location to an image in your computer. Then you should see set of images like the below.

Original Image
Original Image

Image eroded with 3 x 3 kernel
Image eroded with 3 x 3 kernel

Image eroded with 5 x 5 kernel
Image eroded with 5 x 5 kernel


Explanation


Let's go through the above OpenCV program line by line.

// Read the image file
Mat image = imread("D:/My OpenCV Website/Lotus.jpeg");

// Check for failure
if (image.empty())
{
    cout << "Could not open or find the image" << endl;
    cin.get(); //wait for any key press
    return -1;
}

This code segment loads an image from the file "D:/My OpenCV Website/Lotus.jpeg" and returns it as a Mat object. If the returned Mat object is empty, exit the program by returning from the main function. This is an important validation because calling imshow() on empty Mat object might crash your program.

//Erode the image with 3x3 kernel
Mat image_eroded_with_3x3_kernel;
erode(image, image_eroded_with_3x3_kernel, getStructuringElement(MORPH_RECT, Size(3, 3)));

erode() function erodes the image using the specified kernel which determines the neighborhood of a pixel over which the minimum is taken. getStructuringElement(MORPH_RECT, Size(3, 3)) function is used to get the rectangular kernel with the size of 3 x 3 for this morphological operation. The resultant image is stored in the image_eroded_with_3x3_kernel. If the image contains more than one channel (color image has 3 or 4 channels), each channel is processed independently.


//Erode the image with 5x5 kernel
Mat image_eroded_with_5x5_kernel;
erode(image, image_eroded_with_5x5_kernel, getStructuringElement(MORPH_RECT, Size(5, 5)));

erode() function erodes the image using the specified kernel which determines the neighborhood of a pixel over which the minimum is taken. getStructuringElement(MORPH_RECT, Size(5, 5)) function is used to get the rectangular kernel with the size of 5 x 5 for this morphological operation. The resultant image is stored in the image_eroded_with_5x5_kernel. If the image contains more than one channel (color image has 3 or 4 channels), each channel is processed independently.


//Define names of the windows
String window_name = "Lotus";
String window_name_eroded_with_3x3_kernel = "Lotus eroded with 3 x 3 kernel";
String window_name_eroded_with_5x5_kernel = "Lotus eroded with 5 x 5 kernel";

// Create windows with above names
namedWindow(window_name);
namedWindow(window_name_eroded_with_3x3_kernel);
namedWindow(window_name_eroded_with_5x5_kernel);

// Show our images inside the created windows.
imshow(window_name, image);
imshow(window_name_eroded_with_3x3_kernel, image_eroded_with_3x3_kernel);
imshow(window_name_eroded_with_5x5_kernel, image_eroded_with_5x5_kernel);

The above code segment creates windows and shows images in them.

waitKey(0); // Wait for any keystroke in the window

destroyAllWindows(); //destroy all opened windows

The program waits for any keystroke. After any key is pressed, all opened windows will be destroyed.

Summary


In the above section, you have learned,

  • How to load an image from a file
  • How to perform the erode morphological operation on images with a given filter.
  • How to create windows and display images
  • How to wait without exiting the program until the user presses a key
  • How to destroy created windows




Erode video with OpenCV



Now I am going to show you how to perform erode morphological operation on a video using an OpenCV C++ example. This is pretty much similar to the previous example. It is recommended to go through the Play Video from File or Camera first in order to understand the following example better.

//Uncomment the following line if you are compiling this code in Visual Studio
//#include "stdafx.h"

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char* argv[])
{
    //open the video file for reading
    VideoCapture cap("D:/My OpenCV Website/A Herd of Deer Running.mp4");

    // if not success, exit program
    if (cap.isOpened() == false)
    {
        cout << "Cannot open the video file" << endl;
        cin.get(); //wait for any key press
        return -1;
    }



    //Define names of the window
    String window_name_of_original_video = "Original Video";
    String window_name_of_video_eroded_with_5x5_kernel = "Video eroded with 5 x 5 kernel";

    // Create a window with above names
    namedWindow(window_name_of_original_video, WINDOW_NORMAL);
    namedWindow(window_name_of_video_eroded_with_5x5_kernel, WINDOW_NORMAL);

    while (true)
    {
        Mat frame;
        bool bSuccess = cap.read(frame); // read a new frame from video 
        if (bSuccess == false)
        {
            cout << "Found the end of the video" << endl;
            break;
        }

        //erode the frame with 5x5 kernel
        Mat frame_eroded_with_5x5_kernel;
        erode(frame, frame_eroded_with_5x5_kernel, getStructuringElement(MORPH_RECT, Size(5, 5)));

        //show the frames in the created windows
        imshow(window_name_of_original_video, frame);
        imshow(window_name_of_video_eroded_with_5x5_kernel, frame_eroded_with_5x5_kernel);

        //wait for for 10 ms until any key is pressed.  
        //If the 'Esc' key is pressed, break the while loop.
        //If the any other key is pressed, continue the loop 
        //If any key is not pressed withing 10 ms, continue the loop
        if (waitKey(10) == 27)
        {
            cout << "Esc key is pressed by user. Stoppig the video" << endl;
            break;
        }
    }

    return 0;

}

Copy and paste the above code snippet into your IDE and run it. Please note that you have to replace "D:/My OpenCV Website/A Herd of Deer Running.mp4" in the code with a valid location to a video in your computer. Then you should see an eroded video along with the original video.