RasterToNumPyArray

摘要

将栅格转换为 NumPy 数组。

说明

NumPy 数组专用于处理大型数组。很多现有 Python 函数都是为了处理 NumPy 数组而创建的,NumPy 数组是包含在 Python 的 SciPy 科学计算包中的最著名数组。您可能想要将 ArcGIS 栅格转换为 NumPy 数组以

  1. 执行可以应用到 NumPy 数组上的许多现有 Python 函数中的一个(例如,对数据运行过滤器、执行多维分析或使用优化例程)。
  2. 通过访问 NumPy 数组中的各个像元来开发自定义函数(例如,执行邻域记数法、更改各个像元值或者对整个栅格运行累积运算符)。

如果数组的定义(左下角以及行数和列数)超出 in_raster 的范围,则数组值将分配为 NoData。

如果 lower_left_corner 与像元角不重合,则会自动捕捉到最近像元角的左下角,该捕捉方法采用的规则与“捕捉栅格”环境设置中的规则相同。RasterToNumPy 函数内的捕捉操作不会与“捕捉栅格”环境设置相混淆;该函数只使用相同的交互。有关详细信息,请参阅以下内容:

RasterToNumPyArray 支持将多波段栅格直接转换为多维数组 (ndarray)。

  1. 如果输入 Raster 实例基于多波段栅格,则会返回 ndarry,其中第一维的长度表示波段数。该 ndarry 将具有维度(波段、行、列)。
  2. 如果输入 Raster 实例基于单个栅格或多波段栅格中的特定波段,则会返回含维度(行、列)的二维数组。

RasterToNumPyArray 支持将多维栅格数据集直接转换为 NumPy 数组。输出 NumPy 数组是维度为 [rows, cols, slice_count] 的 3D 数组。NumPy 数组中的剖切遵循 mdRaster.slices 中列出的顺序

语法

RasterToNumPyArray (in_raster, {lower_left_corner}, {ncols}, {nrows}, {nodata_to_value})
参数说明数据类型
in_raster

要转换为 NumPy 数组的输入栅格。

Raster
lower_left_corner

可从 in_raster 中的左下角提取处理块以转换为数组。x 值和 y 值采用地图单位。若未指定值,则将使用输入栅格的原点。

(默认值为 None)

Point
ncols

in_raster 中要转换为 NumPy 数组的 lower_left_corner 中的列数。

若未指定值,则将使用输入栅格的列数。

(默认值为 None)

Integer
nrows

in_raster 中要转换为 NumPy 数组的 lower_left_corner 中的行数。

若未指定值,则将使用输入栅格的行数。

(默认值为 None)

Integer
nodata_to_value

在生成的 NumPy 数组中分配 in_raster NoData 值的值。

若未指定值,则将使用 in_raster 的 NoData 值。

(默认值为 None)

Variant
返回值
数据类型说明
NumPyArray

输出的 NumPy 数组。

代码示例

RasterToNumPyArray 示例 1

将栅格数据转换为 NumPy 数组旨在计算栅格中每一行的像元值百分比。然后,将会创建一个新的栅格数据。

import arcpy
import numpy

# Get input Raster properties
inRas = arcpy.Raster('C:/data/inRaster')
lowerLeft = arcpy.Point(inRas.extent.XMin,inRas.extent.YMin)
cellSize = ras.meanCellWidth

# Convert Raster to numpy array
arr = arcpy.RasterToNumPyArray(inRas,nodata_to_value=0)

# Calculate percentage of the row for each cell value
arrSum = arr.sum(1)
arrSum.shape = (arr.shape[0],1)
arrPerc = (arr)/arrSum

#Convert Array to raster (keep the origin and cellsize the same as the input)
newRaster = arcpy.NumPyArrayToRaster(arrPerc,lowerLeft,cellSize,
                                     value_to_nodata=0)
newRaster.save("C:/output/fgdb.gdb/PercentRaster")
RasterToNumPyArray 示例 2

块将对输入多波段栅格进行处理并计算所有波段的像元统计数据。该脚本将多波段栅格转换为三维 NumPy 数组,并通过将该数组划分为数据块的方式对其进行处理。接下来,该脚本将计算块中所有行的平均值,将块 numpy 数组转换成栅格,并通过镶嵌重新组合波段。已创建新的多波段栅格。

# Note that, if the input raster is multiband, the data blocks will also be
# multiband, having dimensions (bands, rows, columns).  Otherwise, they will
# have dimensions of (rows, columns).

import arcpy
import numpy
import os

# Input raster
filein = os.path.join(os.getcwd(),r"input\input.tif")

# Output raster (after processing)
fileout = os.path.join(os.getcwd(),r"output\blockprocessingrdb22.tif")

# Size of processing data block
#  where memorysize = datatypeinbytes * numbands * blocksize^2
blocksize = 512

# ----------------------------------------------------------------------------
# Create raster object from file
myRaster = arcpy.Raster(filein)

# Set environmental variables for output
arcpy.env.overwriteOutput = True
arcpy.env.outputCoordinateSystem = filein
arcpy.env.cellSize = filein

# Loop over data blocks
filelist = []
blocknum = 0
for x in range(0, myRaster.width, blocksize):
    for y in range(0, myRaster.height, blocksize):

        # Lower left coordinate of block (in map units)
        mx = myRaster.extent.XMin + x * myRaster.meanCellWidth
        my = myRaster.extent.YMin + y * myRaster.meanCellHeight
        # Upper right coordinate of block (in cells)
        lx = min([x + blocksize, myRaster.width])
        ly = min([y + blocksize, myRaster.height])
        #   noting that (x, y) is the lower left coordinate (in cells)

        # Extract data block
        myData = arcpy.RasterToNumPyArray(myRaster, arcpy.Point(mx, my),
                                          lx-x, ly-y)

        # PROCESS DATA BLOCK -----------------------------
        # e.g., Calculate mean of each cell of all bands.
        myData -= numpy.mean(myData, axis=0, keepdims=True)
        # ------------------------------------------------

        # Convert data block back to raster
        myRasterBlock = arcpy.NumPyArrayToRaster(myData, arcpy.Point(mx, my),
                                                 myRaster.meanCellWidth,
                                                 myRaster.meanCellHeight)

        # Save on disk temporarily as 'filename_#.ext'
        filetemp = ('_%i.' % blocknum).join(fileout.rsplit('.',1))
        myRasterBlock.save(filetemp)

        # Maintain a list of saved temporary files
        filelist.append(filetemp)
        blocknum += 1

# Mosaic temporary files
arcpy.Mosaic_management(';'.join(filelist[1:]), filelist[0])
if arcpy.Exists(fileout):
    arcpy.Delete_management(fileout)
arcpy.Rename_management(filelist[0], fileout)

# Remove temporary files
for fileitem in filelist:
    if arcpy.Exists(fileitem):
        arcpy.Delete_management(fileitem)

# Release raster objects from memory
del myRasterBlock
del myRaster
# ----------------------------------------------------------------------------
RasterToNumPyArray 示例 3

将多维栅格转换为 NumPy 数组。

# Note that, if the input multidimensional raster is also multiband, the data blocks will have dimensions (bands, rows, columns, slices).  Otherwise, they will
# have dimensions of (rows, columns, slices).

import arcpy
import numpy

# Get input multidimensional Raster 
in_mdim_raster = arcpy.Raster('C:/data/water_temp.nc', True)

lowerLeft = arcpy.Point(in_mdim_raster.extent.XMin,in_mdim_raster.extent.YMin)
blockSize = 512

# Convert Raster to numpy array
arr = arcpy.RasterToNumPyArray(in_mdim_raster, lower_left_corner = lowerLeft, ncols = blockSize, nrows = blockSize, nodata_to_value=0)

# the shape of the numpy array is [rows, cols, slices]
print(arr.shape)

相关主题