取得每个单独的网格单元并确定其流向哪个直接下游单元

时间:2019-07-13 01:45:18

标签: python arrays numpy raster arcpy

我正在尝试获取流向栅格并为每个像元确定下一个下游像元。这是数组:https://drive.google.com/open?id=1Dv0gte4TeLVWSYeBws5RK-5vjGY8fAqQ

我修改了http://hydrology.usu.edu/dtarb/giswr/2014/Exercise5.pdf中的代码 我需要循环来遍历所有单元,而不仅仅是我指定的点。

import arcpy, os, traceback, sys, numpy, math, json
from arcpy import env
from arcpy.sa import *
env.overwriteOutput = True
arcpy.CheckOutExtension("Spatial")

# Local variables: **CHANGE THIS TO YOUR FILE LOCATIONS**
outFlowDirection = Raster (r"C:\Users\funke\Documents\ArcGIS\Projects\Rawkins\Layers\fdr")

# convert raster to array
fdr = arcpy.RasterToNumPyArray(outFlowDirection, nodata_to_value=0)

#determine extent
myExtent = outFlowDirection.extent
upperLeft = outFlowDirection.extent.upperLeft
ux = upperLeft.X
uy = upperLeft.Y
cell_width = outFlowDirection.meanCellWidth
cell_height = outFlowDirection.meanCellHeight

#create array for grid number that’s the same size as the raster
arrayrows = fdr.shape[0]
arraycols = fdr.shape[1]
numOfValues = arrayrows*arraycols 
cellid = np.array(np.arange(1,numOfValues+1)).reshape(arrayrows,arraycols)

#create a point object
my_x = -1010216.70
my_y = 2222761.71
pnt = arcpy.Point(my_x, my_y)

#convert point coordinates into raster indices
c = abs(int((ux-pnt.X)/cell_width))
r = abs(int((uy-pnt.Y)/cell_height))

pntX = pnt.X
pntY = pnt.Y
z = fdr[r,c]                #remember the initial raster index value (D8)
coords = [(pntX,pntY,r,c,z)]    # create a list to store our coordinates

#function to check the value of our flow direction grid and move the point.
def move_to_next_pixel(fdr, row, col):
   value = fdr[row, col]            # get the fdr pixel value (x,y)
   if value == 1:
        col += 1
   elif value == 2:
        col += 1
        row += 1
   elif value == 4:
        row += 1
   elif value == 8:
        row += 1
        col -= 1
   elif value == 16:
        col -= 1
   elif value == 32:
        row -= 1
        col -= 1
   elif value == 64:
        row -= 1
   else: #value == 128:
        row -= 1
        col += 1
   return (row, col)

#loop through values
for row in fdr:
   for cell in row:
      last_c = c
      last_r = r
      r,c = move_to_next_pixel(fdr, r, c)   
      pntX += (c - last_c)*cell_width       #recalculate the coordinates
      pntY += (last_r - r)*cell_height      #recalculate the coordinates
      z = fdr[r,c]                      #get value of current (r,c) 
      coords.append((pntX,pntY,r,c,z))      #save this coordinate to list

numpy.savetxt('output.csv', coords, delimiter=',', fmt='%d') #save array

print ('done')

我希望生成的CSV具有单元格号,行号,列号和to_cell#。

我仍然不知道如何遍历所有单元格!

raster image of data

code output

0 个答案:

没有答案