Python:仅在图像蒙版内执行模糊

问题描述:

我有一个灰度图像和该图像中ROI的二进制掩码.我想对灰度图像执行模糊操作,但只能在蒙版范围内执行.现在,我正在模糊整个图像,而不仅仅是删除蒙版外的项目,但是我不希望蒙版外的像素影响我的投资回报率.有没有建立自定义模糊功能的方法吗?

I have a greyscale image and a binary mask of an ROI in that image. I would like to perform a blur operation on the greyscale image but only within the confines of the mask. Right now I'm blurring the whole image and than just removing items outside the mask, but I don't want pixels outside of the mask affecting my ROI. Is there a way to do this without building a custom blur function?

希望这样:

import scipy
blurredImage = scipy.ndimage.filters.gaussian_filter(img, sigma = 3, weight = myMask)

@stefan:

blur = 3
invmask = np.logical_not(mask).astype(int)

masked = img * mask
remaining = img * invmask

blurred = scipy.ndimage.filters.gaussian_filter(masked, sigma = blur)
blurred = blurred+remaining

扩张方法:

blur = 3
invmask = np.logical_not(mask).astype(int)    
masked = img * mask
masked2 = scipy.ndimage.morphology.grey_dilation(masked,size=(5,5))
masked2 = masked2 *invmask
masked2 = masked + masked2
blurred = scipy.ndimage.filters.gaussian_filter(masked2, sigma = blur)

将线性滤波器应用于受限域的正确方法是使用

The right approach to apply a linear filter to a limited domain is to use Normalized Convolution. This method computes (weighted) means within each neighborhood, then normalizes by the (weighted) number of pixels present in that neighborhood. It does so using only two applications of the filter and some trivial per-pixel operations:

# normalized convolution of image with mask
filter = scipy.ndimage.filters.gaussian_filter(img * mask, sigma = blur)
weights = scipy.ndimage.filters.gaussian_filter(mask, sigma = blur)
filter /= weights
# after normalized convolution, you can choose to delete any data outside the mask:
filter *= mask

请注意,mask不必只是0和1,它可以包含中间值,这些中间值指示您确定"该像素值的正确性.但是通常,丢失数据"只有0,而可用数据只有1.

Note that mask doesn't need to be just 0 and 1, it can contain intermediate values indicating how "certain" you are of the correctness of that pixel's value. But typically it's just 0 for "missing data" and 1 for available data.

gaussian_filter必须以浮点格式进行计算,并返回一个浮点值的图像.整数运算将无法在此处执行正确的操作.

gaussian_filter must do its computations in a floating-point format and return an floating-point-valued image. Integer operations will not do the correct thing here.

这是一个例子:

  • 第二张图片:普通过滤,然后去除遮罩外的东西.这表明掩码之外的数据会影响过滤结果.

  • 2nd image: Plain filtering, then removing the stuff outside the mask. This shows that the data outside the mask influences the result of the filtering.

第三张图片:普通过滤,但首先将遮罩外的内容设置为零.这表明掩码外部的零会影响过滤结果.

3rd image: Plain filtering, but setting stuff outside the mask to zero first. This shows that the zeros outside the mask influence the result of the filtering.

第4张图片:使用归一化卷积:被遮罩区域之外的数据完全不影响过滤.

4th image: Using normalized convolution: the data outside the masked area does not affect the filtering at all.