[英]Convert a color image into single-row numpy array (r1, g1, b1; r2, g2, b2; …)
Could anyone show me how to convert a color image into a single-row NumPy array with (r1, g1, b1; r2, g2, b2; ...)
? 谁能告诉我如何使用
(r1, g1, b1; r2, g2, b2; ...)
将彩色图像转换为单行NumPy数组?
So far I've loaded my image into my image with 512x512px size into (512, 512, 3) numpy array. 到目前为止,我已经将图像以512x512px的尺寸加载到(512,512,3)numpy数组中。 Now I want to convert it into (1 x 786432) array.
现在,我想将其转换为(1 x 786432)数组。
ndarray.flatten()
should do the trick: ndarray.flatten()
应该可以解决问题:
In [15]: image = np.arange(4*4*3).reshape((4, 4, 3))
In [16]: image
Out[16]:
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]],
[[12, 13, 14],
[15, 16, 17],
[18, 19, 20],
[21, 22, 23]],
[[24, 25, 26],
[27, 28, 29],
[30, 31, 32],
[33, 34, 35]],
[[36, 37, 38],
[39, 40, 41],
[42, 43, 44],
[45, 46, 47]]])
In [17]: image.flatten()
Out[17]:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47])
To push everything into a single row, you can use reshape
. 要将所有内容推入一行,可以使用
reshape
。
array.reshape(1, -1)
This will return a 2D view of the array with shape (1, 786432)
, a single row. 这将返回具有
(1, 786432)
形状(1, 786432)
的数组的2D视图。 The method views the array as C order by default so the higher dimensions are "flattened" first (which is what you want in this case). 该方法默认情况下将数组视为C顺序,因此首先将“展平”较大的尺寸(在这种情况下,这是您想要的)。
Alternatively, you could use ravel
to get a back a flat array: 或者,您可以使用
ravel
返回平面数组:
array.ravel()
This difference is that the returned view of the array is 1D: shape (786432,)
. 区别在于数组的返回视图为1D:shape
(786432,)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.