OpenCV(6)-腐蚀和膨胀

腐蚀和膨胀属于形态学操作。

腐蚀和膨胀

腐蚀是指:将卷积核B滑过图像A,找出卷积核区域内最小像素值作为锚点像素值。这一操作可以扩大低像素值区域。
膨胀是指:将卷积核B滑过图像A,找出卷积核区域内最大像素值作为锚点像素值。这一操作可以缩小低像素值区域。

通过前面的卷积可以看出,膨胀相当于“最大值”滤波器,腐蚀相当于”最小值“滤波器。滤波器的形状我们可以自己定义。

其他形态学操作

开运算

先对图像腐蚀,再膨胀

\[\texttt{dst} = \mathrm{open} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \mathrm{erode} ( \texttt{src} , \texttt{element} )) \]

闭运算

先膨胀再腐蚀

\[\texttt{dst} = \mathrm{close} ( \texttt{src} , \texttt{element} )= \mathrm{erode} ( \mathrm{dilate} ( \texttt{src} , \texttt{element} )) \]

形态梯度

膨胀图和腐蚀图之差

\[\texttt{dst} = \mathrm{morph\_grad} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \texttt{src} , \texttt{element} )- \mathrm{erode} ( \texttt{src} , \texttt{element} ) \]

顶冒

原图和开运算图之差

\[\texttt{dst} = \mathrm{tophat} ( \texttt{src} , \texttt{element} )= \texttt{src} - \mathrm{open} ( \texttt{src} , \texttt{element} ) \]

黑冒

闭运算结果和原图之差

\[\texttt{dst} = \mathrm{blackhat} ( \texttt{src} , \texttt{element} )= \mathrm{close} ( \texttt{src} , \texttt{element} )- \texttt{src} \]

实验代码

常用函数

Mat getStructuringElement(int shape, Size ksize, Point anchor=Point(-1,-1))

获取卷积核,卷积核中,对应形状位置的元素都为1.
shape:
MORPH_RECT:矩形
MORPH_ELLIPSE:椭圆
MORPH_CROSS:十字形

ksize:
核大小

void morphologyEx(InputArray src, OutputArray dst, int op, InputArray kernel, Point anchor=Point(-1,-1), int iterations=1, int borderType=BORDER_CONSTANT, const Scalar& borderValue=morphologyDefaultBorderValue() )

src:输入图像
dst:结果图像
op:操作MORPH_OPEN开运算,MORPH_CLOSE闭运算、MORPH_GRADIENT形态梯度、MORPH_TOPHAT钉帽、MORPH_BLACKHAT黑冒

代码

#include <iostream>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>


using namespace cv;
using namespace std;

int main(int argc, char* argv[]){
	const char* path = "";
	Mat img = imread(path);
	if (!img.data){
		cout << "Wrong Image" << endl;
		return -1;
	}

	Mat kern = getStructuringElement(MORPH_RECT, Size(5, 5));

	Mat erosion_img, dilate_img;
	//腐蚀
	erode(img, erosion_img, kern);
	//膨胀
	dilate(img, dilate_img, kern);

	imshow("original image", img);
	imshow("erosion image", erosion_img);
	imshow("dilate image", dilate_img);


	Mat open_mat, close_mat, gradient_mat, tophat_mat, blackhat_mat;
	morphologyEx(img, open_mat, MORPH_OPEN, kern);
	morphologyEx(img, close_mat, MORPH_CLOSE, kern);
	morphologyEx(img, gradient_mat, MORPH_GRADIENT, kern);
	morphologyEx(img, tophat_mat, MORPH_TOPHAT, kern);
	morphologyEx(img, blackhat_mat, MORPH_BLACKHAT, kern);

	imshow("Opening", open_mat);
	imshow("Closing", close_mat);
	imshow("Grandient", gradient_mat);
	imshow("Tohat", tophat_mat);
	imshow("Black", blackhat_mat);

	cvWaitKey(0);
	return 0;
}
posted @ 2016-06-28 23:15  Korbin  阅读(5763)  评论(0编辑  收藏  举报