Disk Structuring Element in Opencv

Disk Structuring Element in Opencv

I know a disk structuring element can be created in MATLAB as following:

se=strel('disk',4); 

 0     0     1     1     1     0     0
 0     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
 0     1     1     1     1     1     0
 0     0     1     1     1     0     0

Is there any function or method or any other way of creating the structuring element same as above in opencv. I know we can manually create it using loops but I just want to know if some function exist for that.

3 Answers

The closest one (not the exact same) you can get in OpenCV is by calling getStructuringElement():

int sz = 4;
cv::Mat se = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(2*sz-1, 2*sz-1));

, which gives the matrix with values

[0, 0, 0, 1, 0, 0, 0;
  0, 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;
  0, 1, 1, 1, 1, 1, 0;
  0, 0, 0, 1, 0, 0, 0]
2
def estructurant(radius):
    kernel = np.zeros((2*radius+1, 2*radius+1) ,np.uint8)
    y,x = np.ogrid[-radius:radius+1, -radius:radius+1]
    mask = x**2 + y**2 <= radius**2
    kernel[mask] = 1
    kernel[0,radius-1:kernel.shape[1]-radius+1] = 1
    kernel[kernel.shape[0]-1,radius-1:kernel.shape[1]-radius+1]= 1
    kernel[radius-1:kernel.shape[0]-radius+1,0] = 1
    kernel[radius-1:kernel.shape[0]-radius+1,kernel.shape[1]-1] = 1
    return kernel

try this

You could also use skimage.morphology.disk, which produces a symmetric result (unlike cv2.getStructuringElement):

>>> disk(4)

array([[0, 0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 1, 1, 1, 1, 1, 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],
       [0, 1, 1, 1, 1, 1, 1, 1, 0],
       [0, 1, 1, 1, 1, 1, 1, 1, 0],
       [0, 0, 1, 1, 1, 1, 1, 0, 0],
       [0, 0, 0, 0, 1, 0, 0, 0, 0]], dtype=uint8)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.