如何将2D矩阵划分为块并将每个块乘以其中心元素?

问题描述 投票:1回答:2

我需要将2D矩阵划分为一组具有一定步幅的2D补丁,然后将每个补丁与其中心元素相乘,然后将每个补丁的元素相加。

感觉上不像卷积,对于矩阵的每个元素都使用单独的内核。

以下是视觉插图。结果矩阵的元素计算如下:

Element 1Element 2Element 3

Element 4Element 5

结果应如下所示:

Result

这是我想出的解决方案:

window_shape = (2, 2)
stride = 1

# Matrix
m = np.arange(1, 17).reshape((4, 4))

# Pad it once per axis to make sure the number of views
# equals the number of elements
m_padded = np.pad(m, (0, 1))

# This function divides the array into `windows`, from:
# https://stackoverflow.com/questions/45960192/using-numpy-as-strided-function-to-create-patches-tiles-rolling-or-sliding-w#45960193
w = window_nd(m_padded, window_shape, stride)
ww, wh, *_ = w.shape
w = w.reshape((ww * wh, 4))  # Two first dimensions multiplied is the number of rows

# Tile each center element for element-wise multiplication
m_tiled = np.tile(m.ravel(), (4, 1)).transpose()

result = (w * m_tiled).sum(axis = 1).reshape(m.shape)

我认为这不是很有效,因为在中间步骤中分配了一些数组。

什么是更好或更有效的方法来完成此任务?

python numpy convolution
2个回答
1
投票

尝试scipy.signal.convolve

scipy.signal.convolve

输出:

from scipy.signal import convolve

window_shape = (2, 2)
stride = 1

# Matrix
m = np.arange(1, 17).reshape((4, 4))

# Pad it once per axis to make sure the number of views
# equals the number of elements
m_padded = np.pad(m, (0, 1))

output = convolve(m_padded, np.ones(window_shape), 'valid') * m
print(output)

0
投票

这是我的答案,它不是那么优雅,需要更多代码行,对不起,但也许会有所帮助:

array([[ 14.,  36.,  66.,  48.],
       [150., 204., 266., 160.],
       [414., 500., 594., 336.],
       [351., 406., 465., 256.]])

输出:

import numpy as np

matrix = np.arange(1, 17).reshape(4, 4)

positions = [(i, j) for i in range(4) for j in range(4)]

for p in positions:
    patch_values = [matrix[c]
                    for c
                    in positions
                    if (c[0] in (p[0], p[0] + 1)
                        and c[1] in (p[1], p[1] + 1))]
    patch_multiplied = [(x * matrix[p])
                       for x
                       in patch_values]
    matrix[p] = sum(patch_multiplied)

print(matrix)
© www.soinside.com 2019 - 2024. All rights reserved.