Skip to main content
 首页 » 编程设计

python之卷积模糊图像-python

2024年12月31日8sharpest

下面的代码几乎可以正常工作 - 我在这里唯一需要的是卷积的输出必须除以 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] 

sample 运行-

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