我正在使用从大图像文件创建的相当大的数组。我在使用太多内存时遇到问题,并决定尝试使用numpy.memmap
数组而不是标准的numpy.array
. 我能够创建 amemmap
并将数据从我的图像文件中分块加载到其中,但我不确定如何将操作结果加载到memmap
.
例如,我的图像文件numpy
作为二进制整数数组读入。我编写了一个函数,该函数将任何单元格区域缓冲(扩展)True
指定数量的单元格。此函数将输入数组转换为Boolean
using array.astype(bool)
。我将如何制作Boolean
由数组创建array.astype(bool)
的新numpy.memmap
数组?
此外,如果有一个True
单元格比指定的缓冲区距离更靠近输入数组的边缘,则该函数将向数组的边缘添加行和/或列,以允许围绕现有True
单元格的完整缓冲区。这会改变数组的形状。可以改变 a 的形状numpy.memmap
吗?
这是我的代码:
def getArray(dataset):
'''Dataset is an instance of the GDALDataset class from the
GDAL library for working with geospatial datasets
'''
chunks = readRaster.GetArrayParams(dataset, chunkSize=5000)
datPath = re.sub(r'\.\w+$', '_temp.dat', dataset.GetDescription())
pathExists = path.exists(datPath)
arr = np.memmap(datPath, dtype=int, mode='r+',
shape=(dataset.RasterYSize, dataset.RasterXSize))
if not pathExists:
for chunk in chunks:
xOff, yOff, xWidth, yWidth = chunk
chunkArr = readRaster.GetArray(dataset, *chunk)
arr[yOff:yOff + yWidth, xOff:xOff + xWidth] = chunkArr
return arr
def Buffer(arr, dist, ring=False, full=True):
'''Applies a buffer to any non-zero raster cells'''
arr = arr.astype(bool)
nzY, nzX = np.nonzero(arr)
minY = np.amin(nzY)
maxY = np.amax(nzY)
minX = np.amin(nzX)
maxX = np.amax(nzX)
if minY - dist < 0:
arr = np.vstack((np.zeros((abs(minY - dist), arr.shape[1]), bool),
arr))
if maxY + dist >= arr.shape[0]:
arr = np.vstack((arr,
np.zeros(((maxY + dist - arr.shape[0] + 1), arr.shape[1]), bool)))
if minX - dist < 0:
arr = np.hstack((np.zeros((arr.shape[0], abs(minX - dist)), bool),
arr))
if maxX + dist >= arr.shape[1]:
arr = np.hstack((arr,
np.zeros((arr.shape[0], (maxX + dist - arr.shape[1] + 1)), bool)))
if dist >= 0: buffOp = binary_dilation
else: buffOp = binary_erosion
bufDist = abs(dist) * 2 + 1
k = np.ones((bufDist, bufDist))
bufArr = buffOp(arr, k)
return bufArr.astype(int)