r.neighbors(1grass)

๐ŸŒธ r.neighbors โ€” GRASS User's Manual ๐ŸŒธ

okay bestie, buckle up, because r.neighbors is genuinely one of those tools that sounds boring and is actually everywhere. it's the <rainbow>GRASS GIS</rainbow> module that takes every cell in a raster and rewrites its value as some function of the cells around it. yes, your little cell has a whole friend group and this module is the group chat administrator.

so the deal is: each cell's category value gets replaced by a function of the category values assigned to the cells around it, and the shiny new values land in an output raster map layer. that's the whole NAME energy right there. ๐Ÿ’…


๐Ÿ”‘ KEYWORDS ๐Ÿ”‘

raster, algebra, statistics, aggregation, neighbor, focal statistics, filter, parallel


โœจ SYNOPSIS โœจ

r.neighbors
r.neighbors --help
r.neighbors [-ac] input=name  [selection=name]  output=name[,name,...]
[size=integer]   [method=string[,string,...]]
[weighting_function=string]   [weighting_factor=float]   [weight=name]
[quantile=float[,float,...]]   [title=phrase]   [nprocs=integer]
[memory=memory in MB]   [--overwrite]  [--help]  [--verbose]  [--quiet]
[--ui]

๐ŸŽ€ Flags ๐ŸŽ€

  • -a โ€” Do not align output with the input. like, the output just does its own thing, no alignment moment.
  • -c โ€” Use a circular neighborhood instead of the default square one. round. iconic. geometry.
  • --overwrite โ€” Allow output files to overwrite existing files. only if you're brave bestie.
  • --help โ€” Print usage summary. the "wait what does this do again" button. ๐Ÿค”
  • --verbose โ€” Verbose module output. it will yap.
  • --quiet โ€” Quiet module output. it will not yap.
  • --ui โ€” Force launching GUI dialog. for when you want buttons instead of typing. ๐Ÿ–ฑ๏ธ

๐Ÿ’– Parameters ๐Ÿ’–

  • input=name [required] โ€” Name of input raster map. this is the thing you're about to โœจprocessโœจ.
  • selection=name โ€” Name of an input raster map to select the cells which should be processed. so like, only some cells get the glow-up, the rest are spared. ๐Ÿซถ
  • output=name[,name,...] [required] โ€” Name for output raster map. (yes, it can be a list, we love options.)
  • size=integer โ€” Neighborhood size. how big is the friend group. Default: 3.
  • method=string[,string,...] โ€” Neighborhood operation. the โœจmain characterโœจ parameter. Options: average, median, mode, minimum, maximum, range, stddev, sum, count, variance, diversity, interspersion, quart1, quart3, perc90, quantile. Default: average.
  • weighting_function=string โ€” Weighting function. Options: none, gaussian, exponential, file. Default: none.
    • none: No weighting
    • gaussian: Gaussian weighting function
    • exponential: Exponential weighting function
    • file: File with a custom weighting matrix
  • weighting_factor=float โ€” Factor used in the selected weighting function (ignored for none and file). so if you're not using those two, this one does absolutely nothing, no cap.
  • weight=name โ€” Text file containing weights.
  • quantile=float[,float,...] โ€” Quantile to calculate for method=quantile. Options: 0.0-1.0.
  • title=phrase โ€” Title for output raster map.
  • nprocs=integer โ€” Number of threads for parallel computing.
    • 0: use OpenMP default
    • >0: use nprocs
    • <0: use MAX-nprocs

Default: 0.

  • memory=memory in MB โ€” Maximum memory to be used (in MB). Cache size for raster rows. Default: 300.

okay so that's part 1 ๐Ÿ’– the rest of the lore is coming, don't go anywhere ๐Ÿฆ‹

๐Ÿ’– DESCRIPTION ๐Ÿ’–

okay so bestie, here's the whole vibe of r.neighbors: it takes every single cell in a raster input map and goes ๐Ÿ‘€ at the values sitting in some "neighborhood" you define around it. Then it spits out a whole new raster map layer where each cell gets a value that's some (user-specified) function of everything in that cell's neighborhood. So like, every cell in the output could literally be the average of the values in its 3 x 3 cell "neighborhood" in the input layer. ๐Ÿ’… And yes, the center cell is also included in the calculation โ€” she's invited to the party, she counts. ๐Ÿ’–

Figure: Illustration for an 3x3 sum neighborhood


๐ŸŒธ OPTIONS ๐ŸŒธ

You must tell it the names of the raster map layers to be used for input and output, the method used to analyze neighborhood values (i.e., the neighborhood function โ€” the operation being performed), and the size of the neighborhood. Non-negotiable, the girl needs her details. โœจ

Optionally you can specify a selection map, so it computes new values only where the raster cells of the selection map are not NULL. And when a cell is NULL? The values from the input map get copied straight into the output map, no questions asked. Super useful for smoothing only parts of an elevation map (pits, peaks, ...). ๐Ÿซถ

Example how to use a selection map with method=average:

input map:

1 1  1 1 1
1 1  1 1 1
1 1 10 1 1
1 1  1 1 1
1 1  1 1 1

selection map, NULL values are marked as *:

* * * * *
* * 1 * *
* 1 1 1 *
* * 1 * *
* * * * *

The output map:

1 1 1 1 1
1 1 2 1 1
1 2 2 2 1
1 1 2 1 1
1 1 1 1 1

Without using the selection map, the output map would look like this:

1 1 1 1 1
1 2 2 2 1
1 2 2 2 1
1 2 2 2 1
1 1 1 1 1

It is also possible to weigh cells within the neighborhood. ๐Ÿ‘‘ This can be either done with a custom weights matrix or by specifying a weighting function.

In order to use a custom weights matrix, file needs to be specified as a weighting_function and a path to a text file containing the weights needs to be given in the weight option.

Alternatively, gaussian and exponential weighting functions can be selected as weighting function.

For the gaussian weighting function, the user specifies the sigma value (ฯƒ) for the gauss filter in the weighting_factor option. The sigma value represents the standard deviation of the gaussian distribution, where the weighting formula for the gaussian filter is defined as follows:

exp(-(x*x+y*y)/(2*ฯƒ^2))/(2*ฯ€*ฯƒ^2)

Lower values for sigma result in a steeper curve, so that more weight is put on cells close to the center of the moving window with a steeper decrease in weights with distance from the center. ๐Ÿ“‰

For the exponential weighting function, the user specifies a factor for an exponential kernel in the weighting_factor. Negative factors result in negative exponential decrease in weights from the center cell. The weighting formula for the exponential kernel is defined as follows:

exp(factor*sqrt(x*x+y*y))

Stronger negative values for the factor result in a steeper curve, so that more weight is put on cells close to the center of the moving window with a steeper decrease in weights with distance from the center. ๐Ÿ”ฅ

Optionally, the user can also run r.neighbors and specify the TITLE to be assigned to the raster map layer output, and select to not align the resolution of the output with that of the input (the -a option). These options are described further below. ๐Ÿ‘‡


๐ŸŒŸ Neighborhood Operation Methods ๐ŸŒŸ

The neighborhood operators determine what new value a center cell in a neighborhood will have after examining values inside its neighboring cells. Each cell in a raster map layer becomes the center cell of a neighborhood as the neighborhood window moves from cell to cell throughout the map layer. r.neighbors can perform the following operations:

  • average โ€” The average value within the neighborhood. In the following example, the result would be: (7*4 + 6 + 5 + 4*3)/9 = 5.6667. The result is rounded to the nearest integer (in this case 6).
   Raw Data     Operation     New Data
   +---+---+---+          +---+---+---+
   | 7 | 7 | 5 |          |   |   |   |
   +---+---+---+ average  +---+---+---+
   | 4 | 7 | 4 |--------->|   | 6 |   |
   +---+---+---+          +---+---+---+
   | 7 | 6 | 4 |          |   |   |   |
   +---+---+---+          +---+---+---+
  • median โ€” The value found half-way through a list of the neighborhood's values, when these are ranged in numerical order.
  • mode โ€” The most frequently occurring value in the neighborhood.
  • minimum โ€” The minimum value within the neighborhood.
  • maximum โ€” The maximum value within the neighborhood.
  • range โ€” The range value within the neighborhood.
  • stddev โ€” The statistical standard deviation of values within the neighborhood (rounded to the nearest integer).
  • sum โ€” The sum of values within the neighborhood.
  • count โ€” The count of filled (not NULL) cells.
  • variance โ€” The statistical variance of values within the neighborhood (rounded to the nearest integer).
  • diversity โ€” The number of different values within the neighborhood. In the above example, the diversity is 4.
  • interspersion โ€” The percentage of cells containing values which differ from the values assigned to the center cell in the neighborhood, plus 1. In the above example, the interspersion is: 5/8 * 100 + 1 = 63.5. The result is rounded to the nearest integer (in this case 64).
  • quart1, quart3 โ€” The result will be the first or the third quartile (equal of 25th and 75th percentiles).
  • perc90 โ€” The result will be the 90th percentile of neighborhood.
  • quantile โ€” Any quantile as specified by "quantile" input parameter.

๐Ÿ“ Neighborhood Size ๐Ÿ“

The neighborhood size specifies which cells surrounding any given cell fall into the neighborhood for that cell. The size must be an odd integer and represents the length of one of the moving window edges in cells. For example, a size value of 3 will result in:

             _ _ _
            |_|_|_|
3 x 3 neighborhood --->  |_|_|_|
            |_|_|_|

๐ŸŽ€ Matrix weights ๐ŸŽ€

A custom matrix can be used if none of the neighborhood operation methods are desirable, by using the weight. This option must be used in conjunction with the size option to specify the matrix size, and file needs to be specified as weighting_function. The weights desired are to be entered into a text file. For example, to calculate the focal mean with a matrix size of 3,

r.neigbors in=input.map out=output.map size=3 weighting_function=file \
weight=weights.txt

The contents of the weight.txt file:

3 3 3
1 4 8
9 5 3

This corresponds to the following 3x3 matrix:

+-+-+-+
|3|3|3|
+-+-+-+
|1|4|8|
+-+-+-+
|9|5|3|
+-+-+-+

To calculate an annulus shaped neighborhood the contents of weight.txt file may be e.g. for size=5:

 0 1 1 1 0
 1 0 0 0 1
 1 0 0 0 1
 1 0 0 0 1
 0 1 1 1 0

The way that weights are used depends upon the specific aggregate (method) being used. However, most of the aggregates have the property that multiplying all of the weights by the same factor won't change the final result (an exception is method=count). Also, most (if not all) of them have the properties that an integer weight of N is equivalent to N occurrences of the cell value, and having all weights equal to one produces the same result as when weights are not used. When weights are used, the calculation for method=average is:

sum(w[i]*x[i]) / sum(w[i])

In the case where all weights are zero, this will end up with both the numerator and denominator to zero, which produces a NULL result. ๐Ÿ’€


๐Ÿšฉ FLAGS ๐Ÿšฉ

  • -a โ€” If specified, r.neighbors will not align the output raster map layer with that of the input raster map layer. The r.neighbors program works in the current geographic region. It is recommended, but not required, that the resolution of the geographic region be the same as that of the raster map layer. By default, if unspecified, r.neighbors will align these geographic region settings.
  • -c โ€” This flag will use a circular neighborhood for the moving analysis window, centered on the current cell.

The exact masks for the first few neighborhood sizes are as follows:

3x3     . X .        5x5    . . X . .    7x7    . . . X . . .
       X O X               . X X X .           . X X X X X .
       . X .               X X O X X           . X X X X X .
                           . X X X .           X X X O X X X
                           . . X . .           . X X X X X .
                                               . X X X X X .
                                               . . . X . . .
9x9    . . . . X . . . .        11x11   . . . . . X . . . . .
      . . X X X X X . .                . . X X X X X X X . .
      . X X X X X X X .                . X X X X X X X X X .
      . X X X X X X X .                . X X X X X X X X X .
      X X X X O X X X X                . X X X X X X X X X .
      . X X X X X X X .                X X X X X O X X X X X
      . X X X X X X X .                . X X X X X X X X X .
      . . X X X X X . .                . X X X X X X X X X .
      . . . . X . . . .                . X X X X X X X X X .
                                       . . X X X X X X X . .
                                       . . . . . X . . . . .

๐Ÿ“ NOTES ๐Ÿ’–

okay so real talk bestie, here's how r.neighbors actually behaves out in the wild:

  • it works in the current geographic region, with the current mask, if there is one ๐Ÿซถ
  • it's recommended (not required, no cap) that the resolution of the geographic region matches the resolution of the raster map layer
  • by default r.neighbors will align those geographic region settings โœจ
  • but you can keep original input and output resolutions that are not aligned by specifying it โ€” e.g. with the -a option

Also very important: r.neighbors doesn't propagate NULLs. It just computes the aggregate over the non-NULL cells in the neighborhood. ๐Ÿ’€ (slay honestly)

The -c flag and the weights parameter are mutually exclusive, periodt. Using both together = error, no exceptions. ๐Ÿšซ

Wanna get differently-shaped neighborhood analysis windows? You can use the weight= parameter to point at a weights file where all values are equal. You can also vary the weights at the edge of the neighborhood according to the proportion of the cell that lies inside the neighborhood circle โ€” which effectively anti-aliases the analysis mask. iconic. ๐ŸŽ€

โš ๏ธ For aggregates where a weighted calculation isn't meaningful โ€” specifically minimum, maximum, diversity and interspersion โ€” the weights get used to create a binary mask: zero means the cell gets ignored, any non-zero value means the cell gets used.

Colour file tea โ˜•: r.neighbors copies the GRASS color files associated with the input raster map layer for those output map layers based on the neighborhood average, median, mode, minimum, and maximum. Because standard deviation, variance, diversity, and interspersion are indices rather than direct correspondents to input values, no color files are copied for those map layers. ๐ŸŽจ

The user should note: although the color file is copied for average neighborhood function output, whether or not the color file actually makes sense for the output depends on the input data values. ๐Ÿ™ˆ

๐Ÿงฎ Propagation of output precision โœจ

Here's the logic that's been implemented, bestie. For any aggregate, two factors affect the output type:

  1. Whether the input map is integer or floating-point.
  2. Whether the weighted or unweighted version of the aggregate is used.

These combine to create four possibilities. The columns below go: integer input with no weights, integer input with weights, float input with no weights, float input with weights โ€” and "yes" means weighted. ๐Ÿ’…

  • average โ€” integer: no โ†’ float, yes โ†’ float; float: no โ†’ float, yes โ†’ float
  • median โ€” integer: no โ†’ [1], yes โ†’ [1]; float: no โ†’ float, yes โ†’ float
  • mode โ€” integer: no โ†’ integer, yes โ†’ integer; float: no โ†’ [2], yes โ†’ [2]
  • minimum โ€” integer: no โ†’ integer, yes โ†’ integer; float: no โ†’ float, yes โ†’ float
  • maximum โ€” integer: no โ†’ integer, yes โ†’ integer; float: no โ†’ float, yes โ†’ float
  • range โ€” integer: no โ†’ integer, yes โ†’ integer; float: no โ†’ float, yes โ†’ float
  • stddev โ€” integer: no โ†’ float, yes โ†’ float; float: no โ†’ float, yes โ†’ float
  • sum โ€” integer: no โ†’ integer, yes โ†’ float; float: no โ†’ float, yes โ†’ float
  • count โ€” integer: no โ†’ integer, yes โ†’ float; float: no โ†’ integer, yes โ†’ float
  • variance โ€” integer: no โ†’ float, yes โ†’ float; float: no โ†’ float, yes โ†’ float
  • diversity โ€” integer: no โ†’ integer, yes โ†’ integer; float: no โ†’ integer, yes โ†’ integer
  • interspersion โ€” integer: no โ†’ integer, yes โ†’ integer; float: no โ†’ integer, yes โ†’ integer
  • quart1 โ€” integer: no โ†’ [1], yes โ†’ [1]; float: no โ†’ float, yes โ†’ float
  • quart3 โ€” integer: no โ†’ [1], yes โ†’ [1]; float: no โ†’ float, yes โ†’ float
  • perc90 โ€” integer: no โ†’ [1], yes โ†’ [1]; float: no โ†’ float, yes โ†’ float
  • quantile โ€” integer: no โ†’ [1], yes โ†’ [1]; float: no โ†’ float, yes โ†’ float

[1] For integer input, quantiles may produce float results from interpolating between adjacent values.

[2] Calculating the mode of floating-point data is essentially meaningless. ๐Ÿ˜ญ


With the current aggregates, there are 5 cases:

  1. Output is always float: average, variance, stddev, quantiles (with interpolation).
  2. Output is always integer: diversity, interspersion.
  3. Output is integer if unweighted, float if weighted: count.
  4. Output matches input: minimum, maximum, range, mode (subject to note 2 above), quantiles (without interpolation).
  5. Output is integer for integer input and unweighted aggregate, otherwise float: sum.

โšก Performance ๐Ÿš€

To enable parallel processing, you can specify the number of threads to be used with the nprocs parameter (default 1). The memory parameter (default 300) can also be provided to determine the size of the buffer for computation. ๐Ÿง โœจ

Figure: Benchmark on the left shows execution time for different number of cells, benchmark in the middle shows execution time for different sizes of neighborhood for a 10000x10000 raster and benchmark on the right shows execution time for different memory size for a 10000x10000 raster. See benchmark scripts in source code. (Intel Core i9-10940X CPU @ 3.30GHz x 28) ๐Ÿ“Š

  • To reduce the memory requirements to minimum, set option memory to zero.
  • To take advantage of the parallelization, GRASS needs to be compiled with OpenMP enabled. ๐Ÿซถ

๐ŸŒˆ EXAMPLES ๐ŸŒˆ

๐Ÿ“ Measure occupancy of neighborhood

Set up 10x10 computational region to aid visual inspection of results:

g.region rows=10 cols=10

Fill 50% of the computational region with randomly located cells. "distance=0" will allow filling adjacent cells.

r.random.cells output=random_cells distance=0 ncells=50

Count non-empty (not NULL) cells in 3x3 neighborhood:

r.neighbors input=random_cells output=counts method=count

Optionally โ€” exclude centre cell from the count (= only look around) ๐Ÿ‘€:

r.mapcalc "count_around = if( isnull(random_cells), counts, counts - 1)"

๐Ÿ‘€ SEE ALSO ๐Ÿ‘‘

g.region, r.clump, r.mapcalc, r.mfilter, r.statistics, r.support


๐Ÿซถ AUTHORS ๐Ÿ’œ

  • Original version: Michael Shapiro, U.S.Army Construction Engineering Research Laboratory
  • Updates for GRASS GIS 7 by Glynn Clements and others

๐Ÿ’ป SOURCE CODE ๐ŸŒธ

Available at: r.neighbors source code (history)

Latest change: Thursday Dec 18 02:17:31 2025 in commit: 3648167c5b1f0a73225e8be71956cfc7739e79c8

Main index | Raster index | Topics index | Keywords index | Graphical index | Full index

ยฉ 2003-2026 GRASS Development Team, GRASS 8.5.0 Reference Manual


and that's the whole page bestie, no cap ๐Ÿ’– this was GRASS 8.5.0, r.neighbors(1grass), last touched Thursday Dec 18 02:17:31 2025 โ€” go aggregate something iconic ๐Ÿ’…โœจ

๐Ÿ“ฆ where this page comes from