官术网_书友最值得收藏!

Creating multidimensional arrays

Arrays need not be limited to lists. In fact, they can have an arbitrary number of dimensions. In machine learning, we will often deal with at least 2D arrays, where the column index stands for the values of a particular feature and the rows contain the actual feature values.

With NumPy, it is easy to create multidimensional arrays from scratch. Let's say that we want to create an array with three rows and five columns, with all the elements initialized to zero. If we don't specify a data type, NumPy will default to using floats:

In [23]: arr_2d = np.zeros((3, 5))
... arr_2d
Out[23]: array([[ 0., 0., 0., 0., 0.],
... [ 0., 0., 0., 0., 0.],
... [ 0., 0., 0., 0., 0.]])

As you probably know from your OpenCV days, this could be interpreted as a 3 x 5 grayscale image with all pixels set to 0 (black). Analogously, if we wanted to create a tiny 2 x 4 pixel image with three color channels (R, G, B), but all pixels set to white, we would use NumPy to create a 3D array with the dimensions, 3 x 2 x 4:

In [24]: arr_float_3d = np.ones((3, 2, 4))
... arr_float_3d
Out[24]: array([[[ 1., 1., 1., 1.],
... [ 1., 1., 1., 1.]],
...
... [[ 1., 1., 1., 1.],
... [ 1., 1., 1., 1.]],
...
... [[ 1., 1., 1., 1.],
... [ 1., 1., 1., 1.]]])

Here, the first dimension defines the color channel (red, green, blue, green, and red in OpenCV). Thus, if this was real image data, we could easily grab the color information in the first channel by slicing the array:

In [25]: arr_float_3d[0, :, :]
Out[25]: array([[ 1., 1., 1., 1.],
... [ 1., 1., 1., 1.]])

In OpenCV, images either come as 32-bit float arrays with values between 0 and 1 or they come as 8-bit integer arrays with values between 0 and 255. Hence, we can also create a 2 x 4 pixel, all-white RGB image using 8-bit integers by specifying the dtype attribute of the NumPy array and multiplying all the ones in the array by 255:

In [26]: arr_uint_3d = np.ones((3, 2, 4), dtype=np.uint8) * 255
... arr_unit_3d
Out[26]: array([[[255, 255, 255, 255],
... [255, 255, 255, 255]],
...
... [[255, 255, 255, 255],
... [255, 255, 255, 255]],
...
... [[255, 255, 255, 255],
... [255, 255, 255, 255]]], dtype=uint8)

We will look at more advanced array manipulations in later chapters.

主站蜘蛛池模板: 甘南县| 安平县| 崇左市| 鄂尔多斯市| 红安县| 玉环县| 石家庄市| 托克逊县| 新化县| 鸡西市| 宾川县| 阜阳市| 临泽县| 昭觉县| 沙雅县| 芦山县| 南昌市| 罗平县| 二连浩特市| 石阡县| 延寿县| 崇州市| 卢湾区| 乡宁县| 南昌县| 黎川县| 汝阳县| 水城县| 临沧市| 永善县| 黄龙县| 民和| 昌图县| 教育| 澎湖县| 伊吾县| 巴南区| 成都市| 永平县| 肇源县| 普兰县|