【发布时间】:2020-07-22 04:07:26
【问题描述】:
我想使用 OpenCV 执行灰度形态膨胀。 这似乎很容易,但我没能做到。 因此,我想知道是否可以使用 OpenCV 来做到这一点?
为了检查结果,我创建了一个比较 OpenCV 和 SciPy 的 MWE。 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 相同的结果?
【问题讨论】:
-
OpenCV 结果对我来说似乎是正确的。我没有得到 Scipy 结果,因为 max_filter 不应该创建新值(原始图像中的 5、26、30 在哪里?)。可能正在进行一些插值。还要检查内核中的拼写错误(5 而不是 0/1)。
-
@Miki 是的,我的内核使用 5 来强调差异。关于 Scipy 和 max_filter,我不知道你在说什么,但根据en.wikipedia.org/wiki/Dilation_(morphology)#Grayscale_dilation 给出的形态膨胀定义,SciPy 的值是正确的。例如,对于 x=[3,3] 和 y=[2,2],值 30 是 image[2,2]+Kernel[1,1]=25+5(请注意,内核索引从 [-1 ,-1] 到 [1,1])。
-
@ThomasSablik 由于 OpenCV 也是一个 C++ 库,因此您可以对 C++ 代码提出相同的问题。
-
来自 scipy doc: " 对于完整且扁平的结构元素的简单情况,可以将其视为滑动窗口上的最大过滤器" 这是 OpenCV 所做的.
-
好的,既然我们同意问题不是灰度图像,而是非平面结构元素……是的,OpenCV 不能这样做。 answers.opencv.org/question/59646/… 但实现起来相当容易;)
标签: python opencv grayscale dilation