我尝试创建一个在矩阵和滤波器之间执行卷积的函数。我设法做了基本的操作,但我偶然发现了切片矩阵的范数(主矩阵的子矩阵),对应于输出中的每个位置。
代码是这样的:
def convol2d(matrix, kernel):
# matrix - input matrix indexed (v, w)
# kernel - filtre indexed (s, t),
# h -output indexed (x, y),
# The output size is calculated by adding smid, tmid to each side of the dimensions of the input image.
norm_filter = np.linalg.norm(kernel) # The norm of the filter
vmax = matrix.shape[0]
wmax = matrix.shape[1]
smax = kernel.shape[0]
tmax = kernel.shape[1]
smid = smax // 2
tmid = tmax // 2
xmax = vmax + 2 * smid
ymax = wmax + 2 * tmid
window_list = [] # Initialized an empty list for storing the submatrix
print vmax
print xmax
h = np.zeros([xmax, ymax], dtype=np.float)
for x in range(xmax):
for y in range(ymax):
s_from = max(smid - x, -smid)
s_to = min((xmax - x) - smid, smid + 1)
t_from = max(tmid - y, -tmid)
t_to = min((ymax - y) - tmid, tmid + 1)
value = 0
for s in range(s_from, s_to):
for t in range(t_from, t_to):
v = x - smid + s
w = y - tmid + t
print matrix[v, w]
value += kernel[smid - s, tmid - t] * matrix[v, w]
# This does not work
window_list.append(matrix[v,w])
norm_window = np.linalg.norm(window_list)
h[x, y] = value / norm_filter * norm_window
return h
例如,我的输入矩阵为A(v, w)
,我希望输出矩阵h (x,y)
中的输出值计算为:
h(x,y) = value/ (norm_of_filer * norm_of_sumbatrix)
感谢您的帮助!
编辑:根据建议,我修改如下:
我修改了这样,但我只附加了第一行,并用于计算而不是整个子矩阵。
`for s in range(s_from, s_to):
for t in range(t_from, t_to):
v = x - smid + s
w = y - tmid + t
value += kernel[smid - s, tmid - t] * matrix[v, w]
window_list.append(matrix[v,w])
window_array = np.asarray(window_list, dtype=float)
window_list = []
norm_window = np.linalg.norm(window_array)
h[x, y] = value / norm_filter * norm_window`
答案 0 :(得分:1)
np.linalg.norm的输入应该是“输入数组”。尝试将矩阵列表转换为数组。 (python: list of matrices to numpy array?)
另外,也许可以将norm_window行移出循环,因为你以后只使用它作为最后一步的评估,其中包含所有内容。实际上,等待循环完成,将完成的列表转换为数组(因此只执行一次)并评估norm_window。