2

我用图像中的数据制作了一个 numpy 数组。我想将 numpy 数组转换为一维数组。

import numpy as np
import matplotlib.image as img

if __name__ == '__main__':

  my_image = img.imread("zebra.jpg")[:,:,0]
  width, height = my_image.shape
  my_image = np.array(my_image)
  img_buffer = my_image.copy()
  img_buffer = img_buffer.reshape(width * height)
  print str(img_buffer.shape)

128x128 图像在这里。

在此处输入图像描述

但是,该程序会打印出 (128, 128)。我想img_buffer成为一个一维数组。如何重塑这个数组?为什么 numpy 实际上不会将数组重塑为一维数组?

4

2 回答 2

4

.reshape返回一个新数组,而不是就地重塑。

顺便说一句,您似乎正在尝试获取图像的字节串 - 您可能想要使用它my_image.tostring()

于 2012-11-08T05:10:43.850 回答
3

reshape不起作用。您的代码不起作用,因为您没有将返回的值分配reshapeimg_buffer.

如果要将数组展平为一维,ravel或者flatten可能是更简单的选择。

>>> img_buffer = img_buffer.ravel()
>>> img_buffer.shape
(16384,)

否则,你会想要这样做:

>>> img_buffer = img_buffer.reshape(np.product(img_buffer.shape))
>>> img_buffer.shape
(16384,)

或者,更简洁地说:

>>> img_buffer = img_buffer.reshape(-1)
>>> img_buffer.shape
(16384,)
于 2012-11-08T05:10:11.050 回答