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 |
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 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 |
![]() |
Image eroded with 3 x 3 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.
Hey, I had a doubt.
ReplyDeleteWhy wasn't the B,G,R layers were dealth with separately for eroding?
That is really great.
ReplyDeleteI have been following your tutorials, thanks
This comment has been removed by the author.
ReplyDeleteGreat post nice thanks!
ReplyDeletevicky stark
ReplyDeleteVery Nice blog for learning new things, thanks for such beautiful blog.kendra karter
Watch and Download world's famous Turkish action drama Kurulus Osman Season 3 in English on link below
ReplyDelete👇
Kurulus Osman Season 3
Kurulus Osman Season 3 Episode 1
On link below
Kurulus Osman Season 3 Episode 1
Crypto trading course
Join on link below
Crypto quantum leap
YouTube course
Be a professional YouTuber and start your carrier
Tube Mastery and Monetization by matt
Best product for tooth pain ,
Cavity ,
Tooth decay ,
And other oral issues
Need of every home
With discount
And digistore money back guarantee
Steel Bite Pro
ReplyDeleteAwesome.. geweldig...grymt bra...fantastisch
acheter permis de conduire en suisse
führerschein kaufen schweiz
rijbewijs Kopen België
titanium arts
ReplyDeleteTATONIC ART CUSTOMING · titanium flat iron TATONIC ROCKING T-TATONIC ROCKING T-TATONIC ROCKING T-TATONIC. This poormansguidetocasinogambling unique and original design is crafted with the use 1등 사이트 of 출장안마 sustainable gri-go.com
Cum să cumpărați permisul de conducere online în 5 până la 7 zile fără examene
ReplyDeletecumpăra permis de conducere
cumpărați permisul conducere online
cumpara permis conducere romanesc
cumpăra permis conducere înregistrat
cumpăra permis conducere România
ReplyDeleteComprar carnet de conducir en nuestra web inscrito en el Dgt en un plazo de 5 a 7 días hábiles sin exámenes y podrá conducir libremente en España y otros países sin ningún problema señor
Comprar Licencia de Conducir
Comprar Carnet de Conducir
Comprar Licencia Conducir Legal
Comprar carnet de conducir
comprar licencias de conducir
comprar carnet conducir dgt
comprar licencia de conducir
Acquista la patente di guida sul nostro sito Web valida nel sistema di database senza esami entro 5-7 giorni lavorativi
ReplyDeletecomprare patente
acquisti la patente guida
come acquistare patente guida
kup prawo jazdy
Comprar Carta de Condução
acheter permis de conduire
köp körkort
acquiste patente di guida
Führerschein in Deutschland im Datenbanksystem registriert ohne Prüfungen innerhalb von 5 bis 7 Werktagen kaufen
ReplyDeleteFührerschein kaufen
eu führerschein kaufen
registrierten Führerschein kaufen
echten führerschein kaufen
deutschen Führerschein kaufen
führerschein kaufen legal
Comprar carta conducao online sem exames no prazo de 5 a 7 dias úteis válido no imt de portugal
ReplyDeleteComprar Carta Condução
carta condução mota
kjøpe førerkort
buy UK driver's license
Comprar Carta de Condução
Carta de Condução Preços
Comprar Carta Condução Verdadeira
Comprar Carta de Mota
koop rijbewijs online geregistreerd in de gemeente binnen 5 tot 7 werkdagen tegen een goedkope prijs zonder examens
ReplyDeleteRijbewijs Kopen België
Rijbewijs Kopen
Rijbewijs b Kopen
Rijbewijs Online Kopen