0

i want to apply convolution2D in Python, i want to apply np.sum() each P[0],P[1] not use for-loops.

import numpy as np

arr = np.array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])

K = np.array([[[1,0,1,1],
              [0,1,0,1 ],
              [1,0,1,1 ],
              [1,1,1,1 ]],
              [[1,1,1,1],
              [1,1,1,1 ],
              [1,1,1,1 ],
              [1,1,1,1 ]]])

P = np.zeros((2, 2, 2))

for i in range(2):
    for j in range(2):
        P[:,i,j] = np.sum(K[:,i:i+3,j:j+3]*arr)
        print(P)

so i did like this, but np.sum did sum all K[0]+K[1]. What can i do?

for i in range(2):
    for j in range(2):
        for k in range(2):
            P[k,i,j] = np.sum(K[k,i:i+3,j:j+3]*arr)
print(P)

i don't want to use this k-for-loops. thanks.

  • Have you tried this? https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.convolve2d.html – John Zwinck Dec 15 '19 at 10:59
  • @JohnZwinck yes, but i hope do not use another packages,, :( – JaehyeonKim Dec 15 '19 at 11:02
  • Then does this help? https://stackoverflow.com/questions/43086557/convolve2d-just-by-using-numpy – John Zwinck Dec 15 '19 at 11:05
  • You will have to use loops or recursion one way or another. If you want to avoid the performance overhead of Python loops, you will have to use another library: either scipy or cython, or numba. – Eli Korvigo Dec 15 '19 at 13:32

1 Answers1

0

You just need to do the sum twice in the loop:

for i in range(2):
    for j in range(2):
        P[:,i,j] = np.sum(np.sum(K[:,i:i+3,j:j+3]*arr, axis=1), axis=1)
        print(P)

Also just a small remark, I would not hard-type dimensions, but use shapes:

for i in range(P.shape[1]):
    for j in range(P.shape[2]):
        P[:,i,j] = np.sum(np.sum(K[:,i:i+arr.shape[0],j:j+arr.shape[1]]*arr, axis=1), axis=1)
        print(P)
FBruzzesi
  • 6,385
  • 3
  • 15
  • 37