Is OpenCV able to perform a grayscale morphological dilate?

2.1k Views Asked by At

I want to use OpenCV to perform a grayscale morphological dilation. This seems very easy but I did not manage to do it. Therefore, I am wondering if it is possible to do it with OpenCV?

To check the results I created a MWE comparing OpenCV and SciPy. Scipy seems to give the expected results while OpenCV do not. Unfortunately, from other constrains I have to use OpenCV and not Scipy and do a grayscale morphological dilation. From the MWE it is seems to be possible to do a binary morphological dilation.

MWE:

import cv2
import scipy
import scipy.ndimage
import numpy as np

print('start test')
image=np.array( [[0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0],
  [0, 0, 25, 0, 0],
  [0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0]] )
Kernel=np.array([[0, 1, 0],
       [1, 1, 1],
       [0, 1, 5]])
print('input')
print(image)

image=image.astype('uint8')
Kernel=Kernel.astype('uint8')
output=cv2.dilate(image, Kernel)
print('OpenCV')
print(output)

Output2=scipy.ndimage.grey_dilation(image, structure=Kernel)
print('Scipy')
print(Output2)

print('end test')

Results:

start test
input
[[ 0  0  0  0  0]
 [ 0  0  0  0  0]
 [ 0  0 25  0  0]
 [ 0  0  0  0  0]
 [ 0  0  0  0  0]]
OpenCV
[[ 0  0  0  0  0]
 [ 0 25 25  0  0]
 [ 0 25 25 25  0]
 [ 0  0 25  0  0]
 [ 0  0  0  0  0]]
Scipy
[[ 5  5  5  5  5]
 [ 5 25 26 25  5]
 [ 5 26 26 26  5]
 [ 5 25 26 30  5]
 [ 5  5  5  5  5]]
end test

So it there a simple way (or an option) to do a grayscale morphological dilation with OpenCV, and obtain the same result than SciPy ?

1

There are 1 best solutions below

1
Alex Alex On

OpenCV used flat structure element:

[[1, 1, 1],
 [0, 1, 1]]

Scipy used non-flat structuring element:

[[1, 1, 1],
 [0, 1, 5]]