原理摘自:http://www.opencv.org.cn/opencvdoc/2.3.2/html/doc/tutorials/imgproc/opening_closing_hats/opening_closing_hats.html
开运算是通过先对图像腐蚀再膨胀实现的。
能够排除小团块物体(假设物体较背景明亮)
请看下面,左图是原图像,右图是采用开运算转换之后的结果图。 观察发现字母拐弯处的白色空间消失。
闭运算是通过先对图像膨胀再腐蚀实现的。
能够排除小型黑洞(黑色区域)。
膨胀图与腐蚀图之差
能够保留物体的边缘轮廓,如下所示:
原图像与开运算结果图之差
闭运算结果图与原图像之差
// ConsoleApplication3_6_23.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include<opencv2/opencv.hpp> #include<iostream> using namespace std; using namespace cv; Mat src,dst; int pro_elem = 0; int pro_size = 0; int pro_operator = 0; const int max_elem = 2; const int max_size = 21; const int max_operator = 4; char* windowName = "Demo"; void Image_pro(int,void*); int _tmain(int argc, _TCHAR* argv[]) { src = imread("hwl.jpg"); if(!src.data) return -1; namedWindow(windowName,CV_WINDOW_AUTOSIZE); createTrackbar("Operator:\n 0:opening-1:closing-2:gradient-3:Top Hat-4: Black Hat", windowName,&pro_operator,max_operator,Image_pro); createTrackbar("Element:\n 0:Rect-1:Cross-2:Ellipse", windowName,&pro_elem,max_elem,Image_pro); createTrackbar("Kernel size:\n 2n+1", windowName,&pro_size,max_size,Image_pro); Image_pro(0,0); waitKey(0); return 0; } void Image_pro(int,void*) { int operation = pro_operator + 2; Mat element = getStructuringElement(pro_elem,Size(2*pro_size+1,2*pro_size+1), Point(pro_size,pro_size)); morphologyEx(src,dst,operation,element); imshow(windowName,dst); }
原文:http://blog.csdn.net/h_wlyfw/article/details/33757483