卷积模糊图像 - python

Convolution bluring image - python

我下面的这段代码几乎可以正常工作 - 我在这里唯一需要的是卷积的输出必须除以 9 并向下舍入。 convolve2d 在某种程度上可能吗?

import scipy
import scipy.signal
import numpy as np

def boxBlur(image):
    matrix = np.array(image)
    W = np.array([[1, 1, 1],
              [1, 1, 1],
              [1, 1, 1]])
    np.pad(matrix, 1, mode='constant')
    return scipy.signal.convolve2d(matrix, W, mode='valid')

所以对于这个例子:

boxBlur([[1,1,1],[1,7,1],[1,1,1]])

现在的输出是[[15]],但应该是[[1]](15/9=1,6666 四舍五入=1)

有没有办法不仅可以在矩阵上使用卷积图像,还可以做点别的。

现在我解决问题的方法是手动遍历数组并将每个单元格除以 9 四舍五入

这就是所谓的统一过滤,因此使用SciPy的uniform_filter,它也应该更快-

from scipy.ndimage import uniform_filter

uniform_filter(image.astype(float))[1:-1,1:-1]

样本运行-

In [38]: np.random.seed(0)
    ...: image = np.random.randint(0,9,(7,7))

In [39]: boxBlur(image)/9.0
Out[39]: 
array([[4.55555556, 5.        , 5.55555556, 5.44444444, 5.11111111],
       [4.44444444, 5.        , 5.        , 4.88888889, 4.22222222],
       [4.33333333, 4.44444444, 3.44444444, 3.44444444, 3.77777778],
       [2.22222222, 2.55555556, 2.88888889, 3.44444444, 3.55555556],
       [2.44444444, 2.11111111, 2.44444444, 3.55555556, 4.33333333]])

In [40]: uniform_filter(image.astype(float))[1:-1,1:-1]
Out[40]: 
array([[4.55555556, 5.        , 5.55555556, 5.44444444, 5.11111111],
       [4.44444444, 5.        , 5.        , 4.88888889, 4.22222222],
       [4.33333333, 4.44444444, 3.44444444, 3.44444444, 3.77777778],
       [2.22222222, 2.55555556, 2.88888889, 3.44444444, 3.55555556],
       [2.44444444, 2.11111111, 2.44444444, 3.55555556, 4.33333333]])

计时 -

In [42]: np.random.seed(0)
    ...: image = np.random.randint(0,9,(7000,7000))

In [43]: %timeit boxBlur(image)/9.0
1 loop, best of 3: 2.11 s per loop

In [44]: %timeit uniform_filter(image.astype(float))[1:-1,1:-1]
1 loop, best of 3: 612 ms per loop

四舍五入

四舍五入,使用原始解决方案,它将是:boxBlur(image)//9。此处等效的是 floor-ing,因此使用 np.floor(),但这可能存在精度问题。因此,我们可能会改为使用 np.round 和给定的小数位数来提高精度,然后使用 .astype(int) -

floor
n = 10 # number of decimal places for precision
np.around(uniform_filter(image.astype(float))[1:-1,1:-1], decimals=n).astype(int)

对于带有整数的输入,另一种方法可能是按比例放大 9 并四舍五入,然后是 floor -

np.round(uniform_filter(image.astype(float))[1:-1,1:-1]*9)//9