2012-11-08 43 views
0

我已经从图像的数据中做出了一个numpy数组。我想将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图像在这里。

enter image description here

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

+0

它看起来像你有一个彩色图像,但你只能阅读图像的每个像素的红色通道。这是你的意图吗? –

+0

谢谢!我的初衷是读取所有的RGB。为什么我只读红色频道? – dangerChihuahua007

+1

@DavidFaux wim说,因为显然你已经很快编辑了这个问题来得到正确的代码,你能不能改回来。它完全混淆有一个问题“为什么这不起作用”与代码工作。 – seberg

回答

1

reshape不到位工作。您的代码无效,因为您没有将由reshape返回的值分配回img_buffer

如果要将阵列展平为一维,则可以使用ravelflatten更简单的选项。

>>> 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,) 
+0

啊谢谢! 'ravel()'做了诡计! – dangerChihuahua007

2

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

顺便说一句,你似乎是试图获取图像的字节串 - 你可能想使用my_image.tostring()代替。

+1

不建议将建议更新到问题中的代码中,因为问题和答案的背景不正确,无法帮助未来的读者! – wim

相关问题