Home > Software design >  ValueError: could not broadcast input array from shape (3,3) into shape (3,)
ValueError: could not broadcast input array from shape (3,3) into shape (3,)

Time:02-16

Hello I am stuck with this error. I am not quite sure what I am doing wrong (img is an image with 3 rgb channels and conversion_array is a 3x3 array).

conversion_array = np.array([[1,0,1.402],[1,-0.344136,-0.714136],[1,1.772,0]], dtype = float)

def encoder_ex5(img):
    new_img = np.zeros(shape = (len(img),len(img[0]), 3 ), dtype = float)
    for j in range(len(img)):
        for k in range(len(img[0])):
            new_img[j][k] =  np.multiply(conversion_array , img[j][k])

    return new_img



img = plt.imread('plant.bmp')
img2 = encoder_ex5(img)

The error shown is the one in the title. Can anyone help me with what I am doing wrong?

CodePudding user response:

The correct function for this case is np.dot not np.multiply.

CodePudding user response:

Where's the error? Traceback?

conversion_array is (3,3) shape, right?

What's the shape of img? 2d, 3d? img[j][k] is better written as img[j,k]. But what's its shape?

new_img is 3d by construction, so new_img[j,k] has shape (3,), right?

Did you check the shape of: np.multiply(conversion_array , img[j,k])? The error says it's (3,3). Do you understand why? You are doing

conversion_array*img[j,k], a (3,3) times a (3,) or scalar, in either case a (3,3). You can't put that in a (3,) slot!

What do you want to do? The other answer suggests using np.dot, matrix multiplication, which with a (3,3) and (3,) would give a (3,).

  • Related