作者:liutiancinet | 来源:互联网 | 2023-10-12 16:32
本博客讲解形态雪中的膨胀和腐蚀操作。使用的函数为:
cv::erode
cv::dilate
形态学操作
简而言之:一组基于形状的图像处理的操作。形态学运算对输入图像应用astructuring元素生成一个输出图像。
最基本的形态操作是两个:腐蚀和膨胀。他们有一个广泛的用途,即:
- 去除噪声
- 单个元素的分离和图像中的分离元素的连接
- 发现图像中的强度颠簸或空洞
我们将简要地解释扩张和侵蚀,使用下面的图像作为一个例子:
Dilation
围绕黑色字母区域的背景 (亮的区域) 的膨胀
Erosion
这个操作是在内核重叠区域上计算一个局部最小值.
随着卷积核B 扫过图像, 计算有卷积核 B 覆盖部分像素的最小值,并用最小值替换在锚定点的图像像素.
和dilation的例子一样,我们可以对原始图像应用腐蚀算子。你可以看到在下面的结果,图像的明亮区域(背景,显然的),变得更薄,而黑暗的区域(“书写”部分)变得更大。
/*** @file Morphology_1.cpp* @brief Erosion and Dilation sample code* @author OpenCV team*/#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"using namespace cv;/// Global variables
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;/** Function Headers */
void Erosion( int, void* );
void Dilation( int, void* );/*** @function main*/
int main( int, char** argv )
{/// Load an imagesrc = imread( argv[1], IMREAD_COLOR );if( src.empty() ){ return -1; }/// Create windowsnamedWindow( "Erosion Demo", WINDOW_AUTOSIZE );namedWindow( "Dilation Demo", WINDOW_AUTOSIZE );moveWindow( "Dilation Demo", src.cols, 0 );/// Create Erosion TrackbarcreateTrackbar( "Element:\n 0: Rect \n 1: Cross \n 2: Ellipse", "Erosion Demo",&erosion_elem, max_elem,Erosion );createTrackbar( "Kernel size:\n 2n +1", "Erosion Demo",&erosion_size, max_kernel_size,Erosion );/// Create Dilation TrackbarcreateTrackbar( "Element:\n 0: Rect \n 1: Cross \n 2: Ellipse", "Dilation Demo",&dilation_elem, max_elem,Dilation );createTrackbar( "Kernel size:\n 2n +1", "Dilation Demo",&dilation_size, max_kernel_size,Dilation );/// Default startErosion( 0, 0 );Dilation( 0, 0 );waitKey(0);return 0;
}//![腐蚀]
/*** @function Erosion*/
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; }//![kernel]Mat element = getStructuringElement( erosion_type,Size( 2*erosion_size + 1, 2*erosion_size+1 ),Point( erosion_size, erosion_size ) );//![kernel]/// Apply the erosion operationerode( src, erosion_dst, element );imshow( "Erosion Demo", erosion_dst );
}
//![腐蚀]//![膨胀]
/*** @function Dilation*/
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 ) );/// Apply the dilation operationdilate( src, dilation_dst, element );imshow( "Dilation Demo", dilation_dst );
}
//![膨胀]
例子