0
我嘗試創建一個函數來執行矩陣和過濾器之間的卷積。我設法做了基本的操作,但是我無意中計算了切片矩陣(主矩陣的子矩陣)的範數,對應於輸出中的每個位置。移動窗口子矩陣的規範
的代碼是這樣的:
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`
我編輯我的問題,與我試過的代碼示例。它僅使用計算中的第一行。 – Litwos
嘗試將window_array = np.asarray移出s循環。你看過window_list和window_array的結構嗎?您可能需要重新整理數組。或者,您可以設置一個適當尺寸的空數組,並在循環時將每個值放入適當位置(通過索引)。希望這是有道理的。 –
這工作。對不起,我遲到的答覆,並感謝您的答案! :) – Litwos