Question

I want to create a disk shaped structuring element on OpenCv. I need my SE to be similar with

sel = strel('disk',5);

I want to do this using

cvstructuringElementEx(cols,rows,anchor_x,anchor_y,shape,*values);

What do I need to do to achieve this and which values of anchor_x and anchor_y give the same center point of SE with MATLAB?

Was it helpful?

Solution

According to the docs, you could try:

cv::Mat sel = cv::getStructuringElement(MORPH_ELLIPSE, cv::Size(9,9));

This gave me the following structuring element:

0    0    0    0    1    0    0    0    0
0    1    1    1    1    1    1    1    0
0    1    1    1    1    1    1    1    0
1    1    1    1    1    1    1    1    1
1    1    1    1    1    1    1    1    1
1    1    1    1    1    1    1    1    1
0    1    1    1    1    1    1    1    0
0    1    1    1    1    1    1    1    0
0    0    0    0    1    0    0    0    0

While in MATLAB I got:

>> getnhood(strel('disk',5))
ans =
     0     0     1     1     1     1     1     0     0
     0     1     1     1     1     1     1     1     0
     1     1     1     1     1     1     1     1     1
     1     1     1     1     1     1     1     1     1
     1     1     1     1     1     1     1     1     1
     1     1     1     1     1     1     1     1     1
     1     1     1     1     1     1     1     1     1
     0     1     1     1     1     1     1     1     0
     0     0     1     1     1     1     1     0     0

So not exactly the same but close enough :)

OTHER TIPS

I needed the exact structuring element as in matlab, so I wrote this (not very elegant) function for my need. It works for shapes with an odd number of rows/columns between 3 and 21 (you can manually add other values (check # zeros in Matlab).

The function is invoked like this:

int Radius = 1;
// following call equivalent to Matlab's sel = getnhood(strel('disk',Radius))
cv::Mat sel = strelDisk(Radius); 

And the actual function is

cv::Mat strelDisk(int Radius){ 
// THIS RETURNS STREL('DISK',RADIUS) LIKE IN MATLAB FOR RADIUS = ODD NUMBER BETWEEN 3-->21
cv::Mat sel((2*Radius-1),(2*Radius-1),CV_8U,cv::Scalar(255));
int borderWidth;
switch (Radius){
case 1: borderWidth = 0; break;
case 3: borderWidth = 0; break;
case 5: borderWidth = 2; break;
case 7: borderWidth = 2; break;
case 9: borderWidth = 4; break;
case 11: borderWidth = 6; break;
case 13: borderWidth = 6; break;
case 15: borderWidth = 8; break;
case 17: borderWidth = 8; break;
case 19: borderWidth = 10; break;
case 21: borderWidth = 10; break;
}
for (int i=0; i<borderWidth; i++){
    for (int j=0; j<borderWidth; j++){
        if (i+j<8){
            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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top