Opencv3從頭開始(六)形態學操作之梯度、頂帽、黑帽
梯度:膨脹圖像-腐蝕圖像。
//梯度
Mat image_gradit;
morphologyEx(image_thre,image_gradit,MORPH_GRADIENT,element);
imshow("梯度",image_gradit);
頂帽:原圖與原圖的開運算的差值圖像,突出明亮區域。
//頂帽
Mat image_top_hat;
morphologyEx(image_thre,image_top_hat,MORPH_TOPHAT,element);
imshow("頂帽",image_top_hat);
黑帽:閉運算與原圖的差值圖像,突出較暗區域。
//黑帽
Mat image_black_hat;
morphologyEx(image_thre,image_black_hat,MORPH_BLACKHAT,element);
imshow("黑帽",image_black_hat);
代碼如下:
/*
形態學操作初步
梯度、頂帽、黑帽
*/
#include<opencv2/opencv.hpp>
#include<opencv2/imgproc.hpp>
#include<opencv2/imgcodecs.hpp>
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int main(int argc, char* argv[]){
Mat image=imread("倉老師.jpg");
Mat image_gray,image_thre;
//二值化
cvtColor(image,image_gray,COLOR_BGR2GRAY);
threshold(image_gray,image_thre,125,255,THRESH_BINARY);
imshow("倉老師",image);
imshow("倉老師黑白",image_thre);
//內核,可選矩形MORPH_RECT、交叉形MORPH_CROSS、橢圓MORPH_ELLIPSE
Mat element=getStructuringElement(MORPH_ELLIPSE,Size(5,5),Point(-1,-1));
//梯度
Mat image_gradit;
morphologyEx(image_thre,image_gradit,MORPH_GRADIENT,element);
imshow("梯度",image_gradit);
//黑帽
Mat image_black_hat;
morphologyEx(image_thre,image_black_hat,MORPH_BLACKHAT,element);
imshow("黑帽",image_black_hat);
//頂帽
Mat image_top_hat;
morphologyEx(image_thre,image_top_hat,MORPH_TOPHAT,element);
imshow("頂帽",image_top_hat);
waitKey(0);
return 0;
}