本人利用python对20年NDVI栅格数据进行sen-mk检验,总文件45G,在读取栅格数据时出现内存溢出错误。在此想请较大家如何修改读取栅格语句,循环释放内存?
for file in os.listdir(path1):
filepath1=os.path.join(path1,file)
filepaths.append(filepath1)
#获取影像数量
num_images=len(filepaths)
#读取影像数据
img1=ras.open(filepaths[0])
#获取影像的投影,高度和宽度
transform1=img1.transform
height1=img1.height
width1=img1.width
array1=img1.read()
img1.close()
#读取所有影像
for path1 in filepaths[1:]:
if path1[-3:]=='tif':
print(path1)
img2=ras.open(path1)
array2=img2.read()
array1=np.vstack((array1,array2))
img2.close()
array1=np.vstack((array1,array2))
File "<__array_function__ internals>", line 180, in vstack
File "E:\pychram\lib\site-packages\numpy\core\shape_base.py", line 282, in vstack
return _nx.concatenate(arrs, 0)
File "<__array_function__ internals>", line 180, in concatenate
numpy.core._exceptions._ArrayMemoryError: Unable to allocate 17.1 GiB for an array with shape (8, 20354, 28112) a
批处理,类似这也的试试
# -*- coding: utf-8 -*-
import os
import arcpy
from arcpy import env
from arcpy.sa import *
arcpy.env.workspace = "e:/MODISNDVI/BYNDVI"
rasters = arcpy.ListRasters("*","tif")
out_path = "e:/MODISNDVI/BYNDVI_cl/"
for raster in rasters:
(filepath, fullname) = os.path.split(raster)
(prename, suffix) = os.path.splitext(fullname)
print(prename)
arcpy.CheckOutExtension("ImageAnalyst") #检查许可
arcpy.CheckOutExtension("spatial") #检查许可
whereClause = "VALUE = -3000" #无效值
outSetNull = SetNull(raster, raster, whereClause) * 0.0001 #去除无效值并乘以0.0001
#outname=r"E:\MODISNDVI\BYNDVI\try1.tif" #输出路径
outSetNull.save(out_path + prename + '_ndvi_qcwxz.tif') #保存数据
print('over')
你这个需要一次性读取所有数据吗?能不能读一个处理完然后再读取下一个,使用同一个变量不断循环重新赋值。
在一个大的 for 循环中读取文件的每一行之前,处理它,并且每隔一段时间运行 gc.collect() 以释放内存空间 . 现在我调用一个函数来读取和处理新线程中的文件块 . 一旦线程结束,内存将自动释放,而不会出现奇怪的性能问题