user288609 user288609 - 1 year ago 85
Python Question

on modifying the shape of numpy array resulting from input image

I am trying to customize an existing code to suit my own need. Originally, the code use

imgs = np.ndarray((total, 1, image_rows, image_cols), dtype=np.uint8)
to store a list of image files in an numpy array format. Iterating the folder, each image file is read as follows
img =, image_name))
It works just fine.
The code is as follows:

image_rows = 420
image_cols = 580
imgs = np.ndarray((total, 1, image_rows, image_cols), dtype=np.uint8)
for image_name in images:
img =, image_name))
img = np.array([img])

In order to suit my own need, I tend to have image file array with the shape
[total, image_rows,image_cols,1]
. In other words, I modified it as
imgs = np.ndarray((total,image_rows, image_cols,1), dtype=np.uint8)
However, running the code causes the following error

imgs[i] = img
ValueError: could not broadcast input array from shape (1,420,580) into shape

Are there any way to change the shape of
, which originally has shape of
after reading from file. How can I change it to
without affecting the corresponding pixel values in the image.

Answer Source

You want to transpose the dimensions. It can be done using the transpose method:

img = img.transpose(1,2,0)

(for your case)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download