Saturday, June 25, 2016

Erode and Dilate using OpenCV

Posted by Md. Hanif Ali Sohag on Saturday, June 25, 2016 in | No comments
Erode and Dilate of an image
In this tutorial you will learn how to erode and dilate an image and how to do it using image processing
Code: 

#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 *) {
	process();
}

void on_size_slider(int, void *) {
	
	size_slider = size_slider % 2 == 0 ? size_slider + 1 : size_slider;
	process();
}

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;
}

Output:





0 comments:

Post a Comment