Skip to content
Advertisement

Python , Convolution

I want to take the part of mat (matrix) after every three slides. The code I have is taking the part of matrix after one slide. I want to take the first 3 by 3 part of the matrix and then slide 3 columns to the right and take 3 by 3 part and so on, going through all the matrix.

n1=np.array(([1,2,3,4,5,6],[7,8,9,10,11,12],[12,13,14,15,16,17],[18,19,20,21,22,23],[24,25,26,27,28,29],[30,31,32,33,34,35]))
print(n1)
k=3
    for i in range(3):
        for j in range(3):
            mat = n1[i:i+k, j:j+k]
            print(mat)

Advertisement

Answer

You can use slicing on both rows and cols like the code bellow… Check out the docs here

import numpy as np

n1=np.array(([1,2,3,4,5,6],[7,8,9,10,11,12],[12,13,14,15,16,17],[18,19,20,21,22,23],[24,25,26,27,28,29],[30,31,32,33,34,35]))
print(n1)

MAX_WIDTH = 3
MAX_HEIGHT = 3

for r in range(0, len(n1[0]), MAX_HEIGHT):
    for c in range(0, len(n1), MAX_WIDTH):
        print(n1[r:r+MAX_HEIGHT, c:c+MAX_WIDTH])
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement