关于修改由输入图像产生的 numpy 数组的形状

on modifying the shape of numpy array resulting from input image

我正在尝试自定义现有代码以满足我自己的需要。最初,代码使用 imgs = np.ndarray((total, 1, image_rows, image_cols), dtype=np.uint8) 以 numpy 数组格式存储图像文件列表。遍历文件夹,每个图片文件读取如下img = skimage.io.imread(os.path.join(train_data_path, image_name)) 效果很好。 代码如下:

 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

为了满足我自己的需要,我倾向于使用形状为[total, image_rows,image_cols,1]的图像文件数组。也就是说,我修改为 imgs = np.ndarray((total,image_rows, image_cols,1), dtype=np.uint8) 然而,运行 代码导致如下错误

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

有什么方法可以改变 img 的形状,它在从文件中读取后原来是 [1,420,580] 的形状。如何将其更改为 [420,580,1] 而不影响图像中相应的像素值。

您想转置尺寸。可以使用转置方法完成:

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

(针对您的情况)