看起来inner 是F 上的 10x5 平均滤波器卷积的结果。这很容易重写为与scipy 的卷积,并且它将与您从 CPU 获得的一样快。但是,由于您在矩阵的边界上遗漏了 5 行和列,因此您必须相应地截断输出 inner 和 inner2 矩阵以便能够比较它们。
import numpy as np
from scipy.signal import convolve2d
F = np.random.rand(100,100)
S = 10*np.random.rand(100,100) + 1
L,C = F.shape
inner = np.zeros((L,C))
outer = np.zeros((L,C))
for l in range(5, L - 5):
for c in range(5, C - 5):
inner[l, c] = np.mean(F[l-5 : l+5 , c-5:c])
outer[l, c] = np.mean(F[l-5 : l+5 , c+5 : c+ 5 + int(S[l, c])])
# if inner[l, c] = np.mean(F[l-5 : l+5 , c-5:c+5]),
# then you should use a 10x10 filter
avg_filter = np.ones((10, 5)) / (10*5)
inner2 = convolve2d(F, avg_filter, mode='valid')
# should be very small (1.262e-13 for me)
print((inner2[:89, :89] - inner[5:94, 5:94]).sum())
outer 的表达式很奇怪,因为您在表达式中添加了这个 int(S[l, c]) 偏移量。我认为您不能将其表示为矩阵计算。
因此,要替换您的双 for 循环,您可以使用 from itertools import product 迭代两个可迭代对象的笛卡尔积,如下所示:
from itertools import product
for (l, c) in product(range(5, L - 5), range(5, C - 5)):
outer[l, c] = np.mean(F[l-5 : l+5 , c+5 : c+ 5 + int(S[l, c])])
从信号处理的角度来看,我不确定outer 矩阵应该是什么。如果您告诉我们您正在尝试做什么,则更容易编写更快的代码并获得所需的效果。