我有一个10波段的光栅图像,并将其读取为数组。
file = "test.tif"
ds = gdal.Open(file)
arr = ds.ReadAsArray()
3D阵列的最终形状如下:(n_bands,y_pixels,x_pixels)
但是,我要使用的软件需要4D阵列作为输入: (n_images,n_pixels_y,n_pixels_x,n_bands)
有没有一种方法可以将栅格读取为具有4D数组指定属性的数组,或者将3D数组转换为4D数组。
我尝试使用np.reshape,但它会更改像素的位置。
array([[[3344, 3344, 3344, ..., 8001, 8001, 8001],
[3344, 3344, 3344, ..., 8001, 8001, 8001],
[3344, 3344, 3344, ..., 8001, 8001, 8001],
...,
[2359, 2359, 2359, ..., 7106, 7106, 7106],
[2359, 2359, 2359, ..., 7106, 7106, 7106],
[2359, 2359, 2359, ..., 7106, 7106, 7106]],
...,
[[3173, 3173, 3431, ..., 5658, 5463, 5463],
[3173, 3173, 3431, ..., 5658, 5463, 5463],
[3393, 3393, 3487, ..., 5767, 5536, 5536],
...,
[1751, 1751, 1722, ..., 2753, 2534, 2534],
[1395, 1395, 1415, ..., 2672, 2521, 2521],
[1395, 1395, 1415, ..., 2672, 2521, 2521]]], dtype=uint16)
arrn=arr.reshape(1,y_pixels,x_pixels,10)
array([[[[3344, 3344, 3344, ..., 2122, 2122, 2122],
[2122, 2122, 1378, ..., 1378, 1420, 1420],
[1420, 1420, 1420, ..., 1435, 1435, 1435],
...,
[8753, 8753, 8753, ..., 8086, 8086, 8086],
[8086, 8086, 6949, ..., 6949, 7091, 7091],
[7091, 7091, 7091, ..., 7633, 7633, 7633]],
...,
[[1944, 1944, 1885, ..., 1846, 1795, 1795],
[1645, 1645, 1366, ..., 1605, 1706, 1706],
[1723, 1723, 1854, ..., 2182, 2270, 2270],
...,
[3057, 3057, 3059, ..., 3150, 3195, 3195],
[3249, 3249, 3180, ..., 3178, 3165, 3165],
[3145, 3145, 3056, ..., 2672, 2521, 2521]]]], dtype=uint16)
答案 0 :(得分:2)
您想要将n_bands轴移动到末端,并在前面添加尺寸。 .reshape
不知道您要这样做,只会重新解释新形状的数据。但是您可以手动将其分为两个步骤,以保持正确的像素顺序:
arr # shape (n_bands, y_pixels, x_pixels)
swapped = np.moveaxis(arr, 0, 2) # shape (y_pixels, x_pixels, n_bands)
arr4d = np.expand_dims(swapped, 0) # shape (1, y_pixels, x_pixels, n_bands)