python - 卷积模糊图像 - 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's 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,所以 use np.floor()
,但这可能存在精度问题。因此,我们可以改为使用np.round
给定的小数位数作为精度,然后使用.astype(int)
-
n = 10 # number of decimal places for precision
np.around(uniform_filter(image.astype(float))[1:-1,1:-1], decimals=n).astype(int)
对于带有整数的输入,另一种方法可能是按比例放大9
然后舍入 -
np.round(uniform_filter(image.astype(float))[1:-1,1:-1]*9)//9
推荐阅读
- css - 如何通过引导设计将 SelectedRowStyle 应用于 gridview
- node.js - 节点试图删除 JOI 模块收到错误警告?
- android - 获取未解决的参考:FirebaseError
- selenium-webdriver - 获取 HTTP 状态 401 - 类型状态报告消息描述 此请求需要在 Firefox 62 中进行 HTTP 身份验证,但在 FF 61.0.2 中工作
- javascript - 使用nodemailer在nodejs中发送邮件时如何在邮件附件和通知中提供写入选项
- azure - Azure AD B2C 身份提供程序
- ionic-framework - 离子 3 通知
- dialogflow-es - Google Actions - 输出响应在循环中重复
- java - 如何最好地参数化字符串
- sql-server - 启动 SQL Server 2017 服务时出错。错误代码 3417