收入囊中
形态梯度
dst=morph_grad(src,element)=dilate(src,element)-erode(src,element)
|
(膨胀公式,灰度图像形态学膨胀与腐蚀此文都有介绍)
腐蚀操作对应的API erode和膨胀是一样的
其他形态学操作函数
|
Morphological gradient:
荷枪实弹
先介绍一个类
class MorphoFeatures { private: int threshold; //用于阀值操作 void applyThreshold(Mat& result) { if (threshold>0) cv::threshold(result, result,threshold, 255, THRESH_BINARY_INV); //注意参数是THRESH_BINARY_INV,当<threshold为255,否则为0,倒过来了 } public: void setThreshold(int x) { threshold = x; } Mat getEdges(const Mat &image) { Mat result; morphologyEx(image,result,MORPH_GRADIENT,Mat()); //直接调用,默认3*3 applyThreshold(result); return result; } };
int main( int, char** argv ) { Mat image; image = imread( argv[1] ); cvtColor( image, image, CV_RGB2GRAY ); MorphoFeatures morpho; morpho.setThreshold(40); Mat edges; edges= morpho.getEdges(image); namedWindow("dstImage", 1); imshow("dstImage", edges); waitKey(); return 0; }
我们再基于公式自己实现一下,修改的地方很少,主函数没有变化(不一样的地方有注释)
class MorphoFeatures { private: int threshold; Mat structedElement; //自己定义的结构矩阵 void applyThreshold(Mat& result) { if (threshold>0) cv::threshold(result, result,threshold, 255, THRESH_BINARY_INV); } public: MorphoFeatures() : structedElement(3,3,CV_8U,Scalar(1)){} //没有使用API而是直接构造 void setThreshold(int x) { threshold = x; } Mat getEdges(const Mat &image) { Mat result,result1,result2; dilate(image,result1,structedElement); //先膨胀 erode(image,result2,structedElement); //再腐蚀 result = result1 - result2; //然后相减 applyThreshold(result); return result; } };
#include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" using namespace cv; class MorphoFeatures { private: int threshold; Mat structedElement; void applyThreshold(Mat& result) { if (threshold>0) cv::threshold(result, result,threshold, 255, THRESH_BINARY_INV); } public: MorphoFeatures() { structedElement = getStructuringElement( MORPH_ELLIPSE, Size( 3, 3 )); } void setThreshold(int x) { threshold = x; } Mat getEdges(const Mat &image) { Mat result,result1,result2; dilate(image,result1,structedElement); erode(image,result2,structedElement); result = result1 - result2; applyThreshold(result); return result; } }; int main( int, char** argv ) { Mat image; image = imread( argv[1] ); cvtColor( image, image, CV_RGB2GRAY ); MorphoFeatures morpho; morpho.setThreshold(40); Mat edges; edges= morpho.getEdges(image); namedWindow("dstImage", 1); imshow("dstImage", edges); waitKey(); return 0; }
OpenCV2马拉松第16圈——边缘检测(形态学梯度),布布扣,bubuko.com
原文地址:http://blog.csdn.net/abcd1992719g/article/details/25599131