Erode and Dilate using OpenCV

Erode and Dilate of an image

The most basic morphological operations are dilation and erosion. Dilation adds pixels to the boundaries of objects in an image, while erosion removes pixels on object boundaries. The number of pixels added or removed from the objects in an image depends on the size and shape of the structuring element used to process the image. In the morphological dilation and erosion operations, the state of any given pixel in the output image is determined by applying a rule to the corresponding pixel and its neighbors in the input image. The rule used to process the pixels defines the operation as a dilation or an erosion. This table lists the rules for both dilation and erosion.

In this tutorial, you will learn how to erode and dilate an image and how to do it using image processing

#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
Mat image, image_processed;

int choice_slider = 0, size_slider = 5, structElement = 0; // 0 - erode, 1 - dilate

void process() {

int Stype;
if (structElement == 0)
Stype = MORPH_RECT; //structure element is Rectangular
else if (structElement == 1)
Stype = MORPH_CROSS; //structure element is Cross
else if (structElement == 2)
Stype = MORPH_ELLIPSE; //structure element is Ellipse


Mat st_elem = getStructuringElement(Stype, Size(size_slider, size_slider));

if (choice_slider == 0) {
erode(image, image_processed, st_elem);
else {
dilate(image, image_processed, st_elem);

imshow("Processed image", image_processed);

void on_choice_slider(int, void *) {

void on_size_slider(int, void *) {

size_slider = size_slider % 2 == 0 ? size_slider + 1 : size_slider;

int main() {

image = imread("c://test//image3.jpg");
namedWindow("Original image");
namedWindow("Processed image");
imshow("Original image", image);

Mat st_elem = getStructuringElement(MORPH_RECT, Size(size_slider, size_slider));
erode(image, image_processed, st_elem);
imshow("Processed image", image_processed);

createTrackbar("Element: n 0: Rect n 1: Cross n 2: Ellipse", "Processed image", &structElement, 2, on_choice_slider);
createTrackbar("Erode/Dilate", "Processed image", &choice_slider, 1, on_choice_slider);
createTrackbar("Kernel Size", "Processed image", &size_slider, 21, on_size_slider);

while (char(waitKey(1) != 'q')) {}

return 0;



eeee Erode and Dilate using OpenCV


life2coding_icon [] Erode and Dilate using OpenCV

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.