gdal WriteArray() 在没有堆栈跟踪的情况下崩溃 python

gdal WriteArray() crashes python without a stack trace

我正在尝试使用 gdal 将数组写入 geotiff。数组的每一行都是相同的,我使用 np.broadcast_to 创建数组。

当我尝试编写它时,我得到一个 windows 弹出窗口说 "Python has stopped working: A problem cause the program to stop working correctly. Please close the program"

这与我正在采取的步骤大致相同:

import gdal
import numpy as np

driver = gdal.GetDriverByName('GTiff')
outRaster = driver.Create("C:/raster.tif", 1000, 1000, 1, 6)
band = outRaster.GetRasterBand(1)

# Create  array 
a = np.arange(0,1000, dtype='float32')
a1 = np.broadcast_to(a, (1000,1000))

# try writing
band.WriteArray(a1) # crash

问题是 broadcast_to 创建的输入数组在磁盘上不连续。如numpy documentation所述,多个元素数组可能指向同一个内存地址。这会导致 gdal 出现问题。

而不是使用 broadcast_to,而是使用将每个元素存储为内存中自己位置的东西。 作为说明性示例,请参见以下代码:

import gdal
import numpy as np
import sys

driver = gdal.GetDriverByName('GTiff')
outRaster = driver.Create("C:/raster.tif", 1000, 1000, 1, 6)
band = outRaster.GetRasterBand(1)

# Create 1000 x 1000 array two different ways
a = np.arange(0,1000, dtype='float32')
a1 = a[np.newaxis, :]
a1 = a1.repeat(1000, axis=0)

a2 = np.broadcast_to(a, (1000,1000))

# examine size of objects
sys.getsizeof(a1) # 4000112
sys.getsizeof(a2) # 112

# try writing
band.WriteArray(a1) # writes fine
band.WriteArray(a2) # crash