Could not broadcast input array from shape into shape [Fix]

Borislav Hadzhiev

Last updated: Apr 11, 2024

Reading timeยท3 min

- Could not broadcast input array from shape into shape [Fix]
- If you have grayscale images, convert them to RGB

**The NumPy error "ValueError: could not broadcast input array from shape"
occurs when at least one of the items in the list you are converting to an array
doesn't match the dimensions or the other elements.**

**To solve the error, make sure the dimensions of all elements in your list
match.**

Here is an example of how the error occurs.

main.py

`import numpy as np a_list = [ np.zeros((1, 2, 3)), np.zeros((1, 2, 3)), np.zeros((1, 2)) # ๐๏ธ ] arr = np.array(a_list) # โ๏ธ ValueError: could not broadcast input array from shape (2,3) into shape (1,2) print(arr)`

Notice that the third item in the list doesn't match the dimensions of the previous two.

You will also get the error if at least one of the lists contains a different number of elements.

main.py

`import numpy as np a_list = [ np.zeros((1, 2, 3)), np.zeros((1, 2, 3)), np.zeros((1, 2, 4)) # ๐๏ธ has 4 elements ] arr = np.array(a_list) # โ๏ธ ValueError: could not broadcast input array from shape (2,3) into shape (1,2) print(arr)`

You will also get the error if one of the sublists is of a different length.

main.py

`import numpy as np a_list = [ np.zeros((1, 2, 3)), np.zeros((1, 2, 3)), np.zeros((1, 3, 3)) # ๐๏ธ sublist with different length ] arr = np.array(a_list) # โ๏ธ ValueError: could not broadcast input array from shape (2,3) into shape (1,) print(arr)`

To solve the error, make sure the shape of the NumPy arrays in the list is consistent.

main.py

`# โ Works import numpy as np a_list = [ np.zeros((1, 2, 3)), np.zeros((1, 2, 3)), np.zeros((1, 2, 3)) ] arr = np.array(a_list) print(arr) print(arr.shape) # ๐๏ธ (3, 1, 2, 3)`

The code for this article is available on GitHub

Running the code sample produces the following output.

shell

`[[[[0. 0. 0.] [0. 0. 0.]]] [[[0. 0. 0.] [0. 0. 0.]]] [[[0. 0. 0.] [0. 0. 0.]]]]`

Each sublist has 1 element - a nested sublist with two elements.

These two elements are lists with three elements.

The NumPy arrays in the list must all be the same size.

In other words, the following code sample raises the error.

main.py

`import numpy as np a_list = [ np.zeros((1, 2)), np.zeros((1, 2)), np.zeros((1, 3)) # ๐๏ธ has 3 elements instead of 2 ] arr = np.array(a_list) # โ ValueError: could not broadcast input array from shape (2,) into shape (1,) print(arr)`

The error is caused because the third array has 3 elements and the other arrays have 2.

The following code sample works as expected because all arrays have the same shape.

main.py

`# โ Works import numpy as np a_list = [ np.zeros((1, 2)), np.zeros((1, 2)), np.zeros((1, 2)) ] arr = np.array(a_list) print(arr)`

The code for this article is available on GitHub

The code sample produces the following output.

main.py

`[[[0. 0.]] [[0. 0.]] [[0. 0.]]]`

If you got the error while trying to process grayscale images, try to convert them to RGB.

main.py

`from PIL import Image img = Image.open('house.jpg').convert('RGB')`

You might also get the error when processing images.

If you have images that are RGB and grayscale formats, you will get a dimensions mismatch.

The grayscale effect is two-dimensional and the original image (RGB) is three-dimensional.

You can also set the dimensions of all images consistently.

main.py

`from PIL import Image img = Image.open('house.jpg').convert( 'RGB').resize((350, 350), Image.LANCZOS)`

The code for this article is available on GitHub

You can also use an `if`

statement to check if each image in your data set has
the correct dimensions before adding them to your training data.

main.py

`import numpy as np from PIL import Image img = np.array(Image.open('house.jpg')) print(img.shape) training_images = [] # ๐๏ธ Check if dimensions are correct before append() if img.shape == (4608, 3456, 3): training_images.append(img) print(training_images)`

The code for this article is available on GitHub

We check if the dimensions of the image are correct before calling list.append().

You can learn more about the related topics by checking out the following tutorials:

- Convert a NumPy array to 0 or 1 based on threshold in Python
- How to get the length of a 2D Array in Python
- TypeError: 'numpy.ndarray' object is not callable in Python
- TypeError: Object of type ndarray is not JSON serializable
- IndexError: too many indices for array in Python [Solved]
- Cannot concatenate object of type 'X'; only Series and DataFrame objs are valid