无法在Python中将图像重塑为二维数组

时间:2019-04-15 11:47:07

标签: python arrays classification reshape

我正在尝试使用以下代码将图像重塑成较长的2d数组(nrow * ncol,nband):

new_shape = (img.shape[0] * img.shape[1], img.shape[2] - 1)

img_as_array = img[:, :, :7].reshape(new_shape)
print('Reshaped from {o} to {n}'.format(o=img.shape,
                                        n=img_as_array.shape))

产生的错误如下:

ValueError                                Traceback (most recent call last)
<ipython-input-205-9de646941a34> in <module>
      2 new_shape = (img.shape[0] * img.shape[1], img.shape[2] - 1)
      3 
----> 4 img_as_array = img[:, :, :7].reshape(new_shape)
      5 print('Reshaped from {o} to {n}'.format(o=img.shape,
      6                                         n=img_as_array.shape))

ValueError: cannot reshape array of size 71696520 into shape (17924130,3)

1 个答案:

答案 0 :(得分:0)

正如我从您的错误中看到的那样,原始图像中有nband == 4,但是在new_shape变量nband == 3中减去了一个。因此重塑的尺寸不匹配。您可以根据自己的问题选择一种解决方案。

new_shape = (img.shape[0] * img.shape[1], img.shape[2]) # 1. don't subtract

img_as_array = img[:, :, :4].reshape(new_shape) # 2. make nband of image smaller