RasterToNumPyArray (arcpy)

摘要

将栅格转换为 NumPy 数组。

讨论

Python 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,其中第一维的长度表示波段数。ndarray 将具有维度(波段、行、列)。
  2. 如果输入Raster实例基于单个栅格或多波段栅格中的特定波段,则会返回含维度(行、列)的二维数组。

语法

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

The input raster to convert to a NumPy array.

Raster
lower_left_corner

The lower left corner within the in_raster from which to extract the processing block to convert to an array. The x- and y-values are in map units. If no value is specified, the origin of the input raster will be used.

(默认值为 None)

Point
ncols

The number of columns from the lower_left_corner in the in_raster to convert to the NumPy array.

If no value is specified, the number of columns of the input raster will be used.

(默认值为 None)

Integer
nrows

The number of rows from the lower_left_corner in the in_raster to convert to the NumPy array.

If no value is specified, the number of rows of the input raster will used.

(默认值为 None)

Integer
nodata_to_value

The value to assign the in_raster NoData values in the resulting NumPy array.

If no value is specified, the NoData value of in_raster will be used.

(默认值为 None)

Variant
返回值
数据类型说明
NumPyArray

输出的 NumPy 数组。

代码实例

RasterToNumPyArray 示例 1

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

import arcpy
import numpy

# Get input Raster properties
inputRaster = 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 (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*nobands*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 = []
blockno = 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.' % blockno).join(fileout.rsplit('.',1))
        myRasterBlock.save(filetemp)

        # Maintain a list of saved temporary files
        filelist.append(filetemp)
        blockno += 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
# ----------------------------------------------------------------------------

相关主题

5/10/2014