on modifying the shape of numpy array resulting from input image

时间:2016-10-20 19:25:07

标签: python numpy scipy computer-vision scikit-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 = skimage.io.imread(os.path.join(train_data_path, 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)
 i=0
 for image_name in images:
     img = skimage.io.imread(os.path.join(train_data_path, image_name))
     img = np.array([img])
     imgs[i]=img
     i+=1

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         
(420,580,1)

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

1 个答案:

答案 0 :(得分:1)

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

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

(for your case)