Невозможно преобразовать изображение в 2d массив в Python - PullRequest
0 голосов
/ 15 апреля 2019

Я пытаюсь преобразовать изображение в длинный двумерный массив (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 голосов
/ 15 апреля 2019

Как я вижу из вашей ошибки, у вас есть 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
...