腐蚀:
Erosion is the sister of dilation. It computes a local minimum over the area of given kernel.
膨胀:
compute the maximal pixel value overlapped by B and replace the image pixel in the anchor point position with that maximal value.
代码示例
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
using namespace cv;
Mat src, erosion_dst, dilation_dst;
int erosion_elem = 0;
int erosion_size = 0;
int dilation_elem = 0;
int dilation_size = 0;
int const max_elem = 2;
int const max_kernel_size = 21;
void Erosion(int, void*);
void Dilation(int, void*);
int main(int, char** argv)
{
const char* filename = "../data/lena.jpg";
src = imread(filename, IMREAD_COLOR);
if (src.empty())
{
return -1;
}
namedWindow("Erosion Demo", WINDOW_AUTOSIZE);
namedWindow("Dilation Demo", WINDOW_AUTOSIZE);
moveWindow("Dilation Demo", src.cols, 0);
createTrackbar("Element", "Erosion Demo", // 腐蚀方法
&erosion_elem, max_elem, Erosion);
createTrackbar("Kernel", "Erosion Demo", // 腐蚀掩模大小
&erosion_size, max_kernel_size, Erosion);
createTrackbar("Element", "Dilation Demo", // 膨胀方法
&dilation_elem, max_elem, Dilation);
createTrackbar("Kernel", "Dilation Demo", // 膨胀掩模大小
&dilation_size, max_kernel_size, Dilation);
Erosion(0, 0);
Dilation(0, 0);
waitKey(0);
return 0;
}
void Erosion(int, void*)
{
int erosion_type = 0;
if (erosion_elem == 0) { erosion_type = MORPH_RECT; }
else if (erosion_elem == 1) { erosion_type = MORPH_CROSS; }
else if (erosion_elem == 2) { erosion_type = MORPH_ELLIPSE; }
Mat element = getStructuringElement(erosion_type,
Size(2 * erosion_size + 1, 2 * erosion_size + 1), Point(erosion_size, erosion_size));
erode(src, erosion_dst, element); // 腐蚀
imshow("Erosion Demo", erosion_dst);
}
void Dilation(int, void*)
{
int dilation_type = 0;
if (dilation_elem == 0) { dilation_type = MORPH_RECT; } // 矩形
else if (dilation_elem == 1) { dilation_type = MORPH_CROSS; } // 十字型
else if (dilation_elem == 2) { dilation_type = MORPH_ELLIPSE; } // 椭圆
Mat element = getStructuringElement(dilation_type,
Size(2 * dilation_size + 1, 2 * dilation_size + 1), Point(dilation_size, dilation_size));
dilate(src, dilation_dst, element); // 膨胀
imshow("Dilation Demo", dilation_dst);
}
运行结果