0

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)

Reti43
  • 9,656
  • 3
  • 28
  • 44
  • When you say you want to reshape an array to (3, 673, 3, 1198), it means you have exactly 7256286 elements. Not x times that. But maybe you want to add another dimension with -1? This will use the remainder for that axis, e.g., (3, 673, 3, 1198, -1) will end up being (3, 673, 3, 1198, 4). This is all addressed in the question you linked, so how does it not answer your question? – Reti43 Nov 08 '21 at 17:43
  • I was going to step through that problem line, `res = ...reshape(...)`, but quickly got lost in the mix of shapes, especially the `img` indexing. This isn't a `googling` issue. It's a matter of getting the mix of shapes, particularly the total number of elements, right. – hpaulj Nov 08 '21 at 19:15
  • Another thought, what `numpydata.shape`? Is it, for example a 4 channel color image? Your shapes only focus on the h/w dimensions. Questions like this need full information - traceback along with the shape and dtype of all arrays in quesitons. – hpaulj Nov 08 '21 at 20:21
  • Before "googling it", di you read (or reread) the `np.reshape` docs? – hpaulj Nov 08 '21 at 20:26

0 Answers0