Opencv2.4學習::形態學處理(三)形態學梯度、頂帽、黑帽
阿新 • • 發佈:2018-12-20
形態學處理(三)
1、腐蝕、膨脹操作
2、開運算、閉運算
3、形態學梯度、頂帽、黑帽
形態學梯度
形態學梯度實為膨脹圖與腐蝕圖之差。
作用:
- 突出高亮區域的外圍
- 為輪廓查詢提供新思路
測試程式碼:
#include<opencv2/core/core.hpp> #include<opencv2/highgui/highgui.hpp> #include<opencv2/imgproc/imgproc.hpp> #include<iostream> using namespace std; using namespace cv; void main() { Mat srcImg = imread("F:\\opencv_re_learn\\hand.jpg"); if (!srcImg.data){ cout << "failed to read" << endl; system("pause"); return; } imshow("src", srcImg); Mat srcGray; cvtColor(srcImg, srcGray, CV_BGR2GRAY); Mat thresh; threshold(srcGray, thresh, 230, 255, CV_THRESH_BINARY_INV); imshow("thresh", thresh); //自定義核 Mat element = getStructuringElement(MORPH_RECT, Size(5, 5)); //形態學梯度 Mat gradient_result; morphologyEx(thresh, gradient_result, MORPH_GRADIENT, element); imshow("形態學梯度", gradient_result); waitKey(0); }
實現效果:
頂帽
原影象與“開運算“的結果圖之差
測試程式碼:
#include<opencv2/core/core.hpp> #include<opencv2/highgui/highgui.hpp> #include<opencv2/imgproc/imgproc.hpp> #include<iostream> using namespace std; using namespace cv; void main() { Mat srcImg = imread("F:\\opencv_re_learn\\test.jpg"); if (!srcImg.data){ cout << "failed to read" << endl; system("pause"); return; } imshow("src", srcImg); Mat srcGray; cvtColor(srcImg, srcGray, CV_BGR2GRAY); Mat thresh; threshold(srcGray, thresh, 230, 255, CV_THRESH_BINARY_INV); imshow("thresh", thresh); //自定義核 Mat element = getStructuringElement(MORPH_RECT, Size(5, 5)); //頂帽 Mat tophat_result; morphologyEx(thresh, tophat_result, MORPH_TOPHAT, element); imshow("頂帽", tophat_result); waitKey(0); }
實現效果:
再進一步,既然已經可以提取這個圖的背景,那麼通過背景與二值化影象異或,即可提取前景。
需在上面程式碼後新增如下:
Mat bit_xor;
bitwise_xor(thresh, tophat_result, bit_xor);
imshow("異或", bit_xor);
實現效果:
黑帽
原影象與“閉運算“的結果圖之差
作用:
- 暫未找到好的例子