首页 文章

使用2D高斯蒙版屏蔽灰度图像失败

提问于
浏览
0

这似乎相当简单,但我没有得到理想的结果 . 有人可以向我解释原因吗?我有下面的代码生成一个2D高斯蒙版,其中心的均值和西格玛为32x32像素图像的图像高度的1/3,如下所示:

def gauss2D(image):
    x,y = image.shape[:2]
    shape = (x,y)
    sigma = 1/3 * min(x,y)
    m,n = [(ss-1.)/2. for ss in shape]
    y,x = np.ogrid[-m:m+1,-n:n+1]
    h = np.exp( -(x*x + y*y) / (2.*sigma*sigma) )
    h[ h < np.finfo(h.dtype).eps*h.max() ] = 0
    h = h / h.max() 
    return h

以下是我想要使用的屏蔽图像:

enter image description here

我用来掩盖图像的代码如下:

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
msk = gauss2D(gray)
masked_data = gray * msk

结果图像是这样的:

enter image description here

一个空白的白色图像,有时在角落里的几个部分显示一些不同的图像 .

我也尝试了一个按位AND来应用掩码,但我一直收到这个我似乎无法解决的错误:

res = cv2.bitwise_and(gray, gray, mask = msk)

cv2.error:OpenCV(3.4.1)/Users/travis/build/skvark/opencv-python/opencv/modules/core/src/arithm.cpp:241:错误:(-215)(mtype == 0 ||函数binary_op中的mtype == 1)&& _mask.sameSize(* psrc1)

1 回答

  • 0

    试试这个,它适合我 .

    import numpy as np
    import scipy.stats as st
    
    def gkern(kernlen=21, nsig=3):
    
    """Returns a 2D Gaussian kernel array."""
    
    interval = (2*nsig+1.)/(kernlen)
    x = np.linspace(-nsig-interval/2., nsig+interval/2., kernlen+1)
    kern1d = np.diff(st.norm.cdf(x))
    kernel_raw = np.sqrt(np.outer(kern1d, kern1d))
    kernel = kernel_raw/kernel_raw.sum()
    return kernel
    

    输入:

    import matplotlib.pyplot as plt
    plt.imshow(gkern(21), interpolation='none')
    

相关问题