I try to convolve an image using the function convolve
, which is written below
(It's conv2d_fast
from Python image convolution using NumPy only):
import numpy as np
from PIL import Image
def convolve(img, krn):
is0, is1 = img.shape[0], img.shape[1]
ks0, ks1 = krn.shape[0], krn.shape[1]
rs0, rs1 = is0 - ks0 + 1, is1 - ks1 + 1
ix0 = np.arange(ks0)[:, None] + np.arange(rs0)[None, :]
ix1 = np.arange(ks1)[:, None] + np.arange(rs1)[None, :]
res = krn[:, None, :, None] * img[(ix0.ravel()[:, None], ix1.ravel()[None, :])].reshape(ks0, rs0, ks1, rs1)
res = res.transpose(1, 3, 0, 2).reshape(rs0, rs1, -1).sum(axis = -1)
return res
My code for image processing:
kernel = np.asarray([[1,1,1],[1,1,1],[0,1,1]])
in_image = Image.open('image.png')
numpydata = np.asarray(in_image)
array_img = convolve(numpydata ,kernel)
I was faced with the error: ValueError: cannot reshape array of size 29025144 into shape (3,673,3,1198)
I google it and find Cannot reshape array of size into shape
but in my case 29025144 divide by a whole for 3*673*3*1198 29025144 = 4 *(3*673*3*1198)
Can you help me, please)