strel 是MATLAB中常用的类型,即是structuring element,用来构建结构元素。opencv中与其相似的函数是getStructuringElement()这个函数。
这里仅仅说是相似主要是因为两者还是有很多区别的。
getStructuringElement()可以获取常用的结构元素的形状:矩形(MORPH_RECT)、椭圆(MORPH_ELLIPSE)及十字形(MORPH_CROSS)。
strel 能构建的结构元素更多,但与getStructuringElement()对应的且能直接实现也就只有‘square’/'rectangle'矩形了吧!
列如:
strel('square', 3)
就可以由
Mat ele = getStructuringElement(MORPH_RECT, Size(3, 3));
来实现。
理论上getStructuringElement()在Size(n,n)时构造的应该是个圆,事实上并不是,它依然是个椭圆。所以,getStructuringElement()可能并不能根据需要随时构造出圆形结构元素。
为了方便调试,我们可能需要通过改变半径轻松的得到圆形结构元素。算是皇天不负有心人吧最终得出了通式,具体怎么推出来就不解释了,下面是构造任意半径圆形结构的C代码。
//matlab strel('disk',Radius)
Mat strelDisk(int Radius)
{int borderWidth; Mat sel; int m, n;switch (Radius){case 1: case 2: if (Radius == 1) borderWidth = 1;elseborderWidth = 2;sel=Mat((2 * Radius + 1), (2 * Radius + 1), CV_8U, cv::Scalar(1));break;//当半径为1时是3X3的 ,当半径为2时是5X5的case 3:borderWidth = 0;sel=Mat((2 * Radius - 1), (2 * Radius - 1), CV_8U, cv::Scalar(1)); break;default:n = Radius / 7; m = Radius % 7;if (m == 0 || m >= 4)borderWidth = 2 * (2 * n + 1);elseborderWidth = 2 * 2 * n;sel=Mat((2 * Radius - 1), (2 * Radius - 1), CV_8U, cv::Scalar(1));break; }for (int i = 0; i < borderWidth; i++){for (int j = 0; j < borderWidth; j++){if (i + j < borderWidth){sel.at<uchar>(i, j) = 0;sel.at<uchar>(i, sel.cols - 1 - j) = 0;sel.at<uchar>(sel.rows - 1 - i, j) = 0;sel.at<uchar>(sel.rows - 1 - i, sel.cols - 1 - j) = 0;}}}return sel;
}