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;
else
borderWidth = 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);
else
borderWidth = 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(i, j) = 0;
sel.at(i, sel.cols - 1 - j) = 0;
sel.at(sel.rows - 1 - i, j) = 0;
sel.at(sel.rows - 1 - i, sel.cols - 1 - j) = 0;
}
}
}
return sel;
}