opencv学习之路(15)、形态学其他操作(开、闭、顶帽、黑帽、形态学梯度)
一、形态学其他操作(用的不多,如果忘了也可以通过膨胀腐蚀得到相同效果)
1.开运算
2.闭运算
3.形态学梯度
4.顶帽
5.黑帽
1 #include "opencv2/opencv.hpp" 2 using namespace cv; 3 4 void main() 5 { 6 Mat srcImg = imread("E://1.jpg"); 7 Mat dstImg; 8 Mat element = getStructuringElement(MORPH_RECT, Size(5, 5)); 9 10 //morphologyEx(srcImg, dstImg, MORPH_OPEN, element); //开运算 11 //morphologyEx(srcImg, dstImg, MORPH_CLOSE, element); //闭运算 12 //morphologyEx(srcImg, dstImg, MORPH_GRADIENT, element); //形态学梯度运算 13 //morphologyEx(srcImg, dstImg, MORPH_TOPHAT, element); //顶帽运算 14 morphologyEx(srcImg, dstImg, MORPH_BLACKHAT, element); //黒帽运算 15 16 imshow("src", srcImg); 17 imshow("dst", dstImg); 18 waitKey(0); 19 }
二、小应用(找出差异,对差异进行操作)
1 #include "opencv2/opencv.hpp" 2 using namespace cv; 3 4 void main() 5 { 6 Mat img1=imread("E://A.jpg"); 7 Mat img2=imread("E://B.jpg"); 8 Mat diff; 9 absdiff(img1,img2,diff);//用这个做减法可以避免出现负值=0的情况 10 imshow("img1",img1); 11 imshow("img2",img2); 12 imshow("diff",diff); 13 14 Mat gray; 15 cvtColor(diff,gray,COLOR_BGR2GRAY);//转为灰度图 16 //adaptiveThreshold(gray,gray,255,ADAPTIVE_THRESH_GAUSSIAN_C,THRESH_BINARY_INV,15,3);//自适应阈值有点不懂 17 threshold(gray,gray,5,255,THRESH_BINARY); 18 imshow("threshold",gray); 19 20 //进行形态学操作 21 Mat element=getStructuringElement(MORPH_RECT,Size(3,3));//定义结构元素 22 morphologyEx(gray,gray,MORPH_OPEN,element);//开运算 23 medianBlur(gray,gray,9);//中值滤波 24 dilate(gray,gray,element); 25 imshow("dst",gray); 26 27 waitKey(0); 28 }