convolve matrix in python

To perform convolution of a matrix in Python, we can use the convolve function from the numpy library. Here's an example:

main.py
import numpy as np

# define matrix and kernel to convolve with
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
kernel = np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]])

# perform convolution with zero padding and stride of 1
output = np.zeros_like(matrix)
for i in range(matrix.shape[0] - kernel.shape[0] + 1):
    for j in range(matrix.shape[1] - kernel.shape[1] + 1):
        output[i, j] = np.sum(matrix[i:i+kernel.shape[0], j:j+kernel.shape[1]] * kernel)

print(output)
479 chars
14 lines

In this example, we first define a 3x3 matrix matrix and a 3x3 kernel kernel to convolve with. We then create an output matrix output with the same shape as matrix.

We then perform convolution by looping over each position in output and computing the dot product of the corresponding elements of matrix and kernel. We use zero padding and a stride of 1 to ensure that the output is the same size as the input.

The resulting output matrix is the result of the convolution operation. This same process can be extended to higher dimensions for convolutional neural networks.

gistlibby LogSnag