OpenCV是否能够执行灰度形态放大?

2024-05-15 11:00:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用OpenCV执行灰度形态学膨胀。 这似乎很容易,但我没有做到。 因此,我想知道是否有可能用OpenCV来实现它

为了检查结果,我创建了一个MWE,比较OpenCV和SciPy。 Scipy似乎给出了预期的结果,而OpenCV则没有。不幸的是,由于其他限制,我不得不使用OpenCV而不是Scipy,并进行灰度形态学膨胀。 从MWE来看,似乎可以进行二元形态扩张

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')

结果:

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

因此,有没有一种简单的方法(或选项)用OpenCV进行灰度形态学膨胀,并获得与SciPy相同的结果


Tags: testimageimportnpscipycv2kernelopencv