# GROUPS adjacent slightly different cells
# extension - Spatial Analyst
import arcpy, traceback, sys
from arcpy import env
env.overwriteOutput = True
import numpy
try:
def showPyMessage():
arcpy.AddMessage(str(time.ctime()) + " - " + message)
# load input raster to array and define it's size, origin point, cell size
# replace line below. Consider converting tif to integer grid
raster=arcpy.Raster('C:/FELIX_DATA/theDates')
myArray = arcpy.RasterToNumPyArray(raster,"","","",-9999)
nRows,nCols=myArray.shape
cellsTotal=nCols*nRows
d=arcpy.Describe(raster)
origin=d.extent.lowerLeft
cSize=raster.meanCellHeight
# raster to store assigned group number. Set to -1
blankR=raster-raster-1
blank = arcpy.RasterToNumPyArray(blankR,"","","",-9999)
# directions to find cell neighbour
dRow=(0,-1,-1,-1,0,1,1,1)
dCol=(1,1,0,-1,-1,-1,0,1)
# group counter
groupNo=0
arcpy.SetProgressor("step", "", 0, cellsTotal)
for nRow in range(nRows):
for nCol in range (nCols):
# unassigned cell value = -1
inGroup=blank[nRow,nCol]
if inGroup==-1:
groupNo+=1
blank[nRow,nCol]=groupNo
lstInit=[(nRow,nCol)]
lst2grow=[]
while len(lstInit)>0:
for cell in lstInit:
nR,nC=cell
v=myArray[nR,nC]
for i in xrange(8):
curRow=nR+dRow[i]
curCol=nC+dCol[i]
if curRow in range(nRows) and curCol in range(nCols):
inGroup=blank[curRow,curCol]
if inGroup==-1:
vCur=myArray[curRow,curCol]
if vCur in xrange(v-1,v+2):
blank[curRow,curCol]=groupNo
lst2grow.append((curRow,curCol))
arcpy.SetProgressorPosition()
lstInit=lst2grow[:]
lst2grow=[]
arcpy.SetProgressorLabel("Groups found %i" %groupNo)
del myArray
myRaster = arcpy.NumPyArrayToRaster(blank,origin,cSize,cSize)
del blank
# replace line below
myRaster.save('C:/FELIX_DATA/groups')
except:
message = "\n*** PYTHON ERRORS *** "; showPyMessage()
message = "Python Traceback Info: " + traceback.format_tb(sys.exc_info()[2])[0]; showPyMessage()
message = "Python Error Info: " + str(sys.exc_type)+ ": " + str(sys.exc_value) + "\n"; showPyMessage()