【Python学习笔记】计算2维卷积

M为10×10的二维矩阵,N为3×3的卷积核,计算卷积M\otimesN。

# -*- coding: utf-8 -*-
import numpy as np

print('输入二维矩阵,以空格隔开')

list_M = []
matrix_M = np.zeros((10, 10))
for i in range(10):
    list_M.append(input(f'二维矩阵M:第{i}行:\n'))
for r in range(10):
    for c in range(10):
        matrix_M[r][c] = int(list_M[r].split(' ')[c])

list_N = []
matrix_N = np.zeros((3, 3))
for j in range(3):
    list_N.append(input(f'二维矩阵N:第{j}行:\n'))

for r in range(3):
    for c in range(3):
        matrix_N[r][c] = int(list_N[r].split(' ')[c])


def conv2d(m, n):
    [h, w] = m.shape
    [k, _] = n.shape
    p = int(k / 2)
    padding_m = np.zeros([h + 2, w + 2], np.float32)
    conv_out = np.zeros([h, w], np.float32)
    padding_m[1:h + 1, 1:w + 1] = m

    for i in range(1, h + 1):
        for j in range(1, w + 1):
            roi = padding_m[i - p:i + p + 1, j - p:j + p + 1]
            conv_out[i - 1][j - 1] = np.sum(roi * n)
    return conv_out


M_N = conv2d(matrix_M, matrix_N)
print(M_N)

你可能感兴趣的:(Python学习笔记,python)