This sample code demonstrates how to perform focal statistics using INeighborhoodOp::FocalStatistics method
How to use
- Run ArcMap and add a raster dataset.
- Make sure the Spatial Analyst Extension is checked.
- Add reference to ESRI SpatialAnalyst Object Library.
- Add reference to ESRI GeoAnalyst Object Library.
- Paste the code into VBA.
- Run the sub from the Macros dialog.
Sub FocalStatistics()
'Get the focused map from MapDocument
Dim pMxDoc As IMxDocument
Set pMxDoc = ThisDocument
Dim pMap As IMap
Set pMap = pMxDoc.FocusMap
'Get the input raster from the first layer in ArcMap
Dim pLayer As ILayer
Dim pRasLayer As IRasterLayer
Dim pInRaster As IRaster
Set pLayer = pMap.Layer(0)
If Not TypeOf pLayer Is IRasterLayer Then
Exit Sub
End If
Set pRasLayer = pLayer
Set pInRaster = pRasLayer.Raster
'Create a RasterNeighborhoodOp operator
Dim pNeighborhoodOp As INeighborhoodOp
Set pNeighborhoodOp = New RasterNeighborhoodOp
'Set output workspace
Dim pEnv As IRasterAnalysisEnvironment
Set pEnv = pNeighborhoodOp
Dim pWS As IWorkspace
Dim pWSF As IWorkspaceFactory
Set pWSF = New RasterWorkspaceFactory
Set pWS = pWSF.OpenFromFile("c:\temp", 0)
Set pEnv.OutWorkspace = pWS
'Specify a rectangle neighborhood of 3 by 3 cells
Dim pRasterNeighborhood As IRasterNeighborhood
Set pRasterNeighborhood = New RasterNeighborhood
pRasterNeighborhood.SetRectangle 3, 3, esriUnitsCells
'Perform focal statistics
Dim pOutRaster As IRaster
Set pOutRaster = pNeighborhoodOp.FocalStatistics(pInRaster, esriGeoAnalysisStatsMean, pRasterNeighborhood, True)
'Add output into ArcMap as a raster layer
Dim pOutRasLayer As IRasterLayer
Set pOutRasLayer = New RasterLayer
pOutRasLayer.CreateFromRaster pOutRaster
pMap.AddLayer pOutRasLayer
End Sub