r.neighbors(1)

๐Ÿ’– r.neighbors โ€” the GRASS GIS manual, but make it bestie ๐Ÿ’–

okay so. welcome to r.neighbors(1), the GRASS GIS module that looks at every single cell in your raster and goes "hmm what are your neighbors doing tho" and then rewrites that cell based on them. iconic behavior honestly.


โœจ NAME โœจ

r.neighbors โ€” makes each cell category value a function of the category values assigned to the cells around it, and stores new cell values in an output raster map layer.

like. it's a glow-up for your raster. every cell gets a makeover based on the vibes of the cells surrounding it. periodt.


๐ŸŽ€ KEYWORDS ๐ŸŽ€

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

iykyk ๐Ÿ’…


๐Ÿฆ‹ 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, let it be free, let it be off-grid, main character energy fr.
  • -c โ€” use a circular neighborhood instead of whatever square situation is going on. round = cuter, and also mathematically meaningful.
  • --overwrite โ€” allow output files to overwrite existing files. yes bestie, we're replacing them, no cap.
  • --help โ€” print usage summary. your little cheat sheet ๐Ÿซถ
  • --verbose โ€” verbose module output. it will literally tell you everything.
  • --quiet โ€” quiet module output. shhh. no talking.
  • --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 one you're reading from, the source material, the blueprint.
  • selection=name โ€” name of an input raster map to select the cells which should be processed. so like, only the chosen ones get the treatment. very exclusive. very VIP. ๐Ÿ‘‘
  • output=name[,name,...] [required] โ€” name for output raster map. and yeah you can give it MULTIPLE names, separated by commas, because sometimes one output just isn't enough for you.
  • size=integer โ€” neighborhood size.
    • Default: 3
    • so a size of 3 means a 3x3 little squad around each cell. that's the default and it's giving cozy.
  • method=string[,string,...] โ€” neighborhood operation.
    • Options: average, median, mode, minimum, maximum, range, stddev, sum, count, variance, diversity, interspersion, quart1, quart3, perc90, quantile
    • Default: average
    • yes you can stack multiple methods with commas, go off, collect them all like pokรฉmon ๐Ÿ’–
  • weighting_function=string โ€” weighting function.
    • Options: none, gaussian, exponential, file
    • Default: none
    • none: no weighting. everyone gets equal say, very democratic.
    • gaussian: gaussian weighting function. bell curve but make it neighborly ๐ŸŒˆ
    • exponential: exponential weighting function. decays fast, dramatic queen.
    • file: file with a custom weighting matrix. bring your own, we love a DIY moment.
  • weighting_factor=float โ€” factor used in the selected weighting function (ignored for none and file). so if you picked none or file, this does nothing, it's just sitting there. ๐Ÿ™ˆ
  • weight=name โ€” text file containing weights. the receipts. the exact numbers you want applied.
  • quantile=float[,float,...] โ€” quantile to calculate for method=quantile.
    • Options: 0.0-1.0
    • so any float from 0.0 to 1.0, and yes, plural, comma-separate them if you're feeling ambitious.
  • title=phrase โ€” title for output raster map. give your baby a name, a little description, a legacy โœจ
  • nprocs=integer โ€” number of threads for parallel computing.
    • Default: 1
    • crank it up if you want it to go zoom zoom ๐Ÿ”ฅ
  • memory=memory in MB โ€” maximum memory to be used (in MB).
    • Cache size for raster rows
    • Default: 300
    • this is how much RAM it's allowed to snack on. don't starve it.

more parts incoming bestie, don't go anywhere ๐Ÿ’…

โœจ DESCRIPTION โœจ

okay so bestie, meet r.neighbors โ€” the nosiest neighbor on the block and honestly? iconic ๐Ÿ’…. What it does is it rolls up on every single cell in a raster input map and snoops on the values of the cells sitting in some user-defined "neighborhood" around it. Then it spits out a brand new raster map layer where every cell got handed a value that's some (user-specified) function of the values in that cell's neighborhood. Like, each cell in the output layer might be assigned the average of the values in its 3 x 3 cell "neighborhood" in the input layer. And do not forget โ€” the centre cell is also included in the calculation. it's in the group chat too, no cap ๐Ÿซถ.

Figure: Illustration for an 3x3 average neighborhood


๐ŸŒธ OPTIONS ๐ŸŒธ

You must tell it: the names of the raster map layers for input and output, the method used to analyze neighborhood values (aka the neighborhood function / operation being performed), and the size of the neighborhood. That's the mandatory trio, no skipping ๐ŸŽ€.

You can optionally also hand it a selection map, so it only computes new values where the raster cells of the selection map are not NULL. And when a cell is NULL? The values from the input map just get copied straight into the output map. Super useful for smoothing only parts of an elevation map (pits, peaks, ...). lowkey chef's kiss ๐Ÿ‘‘

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

See the difference? the vibe check on that 10 hits different when you gate it ๐ŸŒˆ

It is also possible to weigh cells within the neighborhood. You can do this either with a custom weights matrix or by specifying a weighting function. ๐Ÿ’…

In order to use a custom weights matrix, the 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, you specify 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, you specify 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, you can also, when running r.neighbors, specify the TITLE to be assigned to the raster map layer output, or 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 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 the 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])
โš ๏ธ heads up bestie โš ๏ธ 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. it's giving "divided by zero, but make it graceful" ๐Ÿ’€

๐ŸŽ€ 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 bestie so real talk: r.neighbors does its thing in the current geographic region with the current mask, if there is one. ๐Ÿ’–

Now, it's recommended (but not required, no pressure) that the resolution of the geographic region matches the resolution of the raster map layer. By default, r.neighbors will align these geographic region settings. But you can choose to keep original input and output resolutions that are not aligned by specifying this (like, for example, by using the -a option). โœจ

Also important: r.neighbors doesn't propagate NULLs. It computes the aggregate over the non-NULL cells in the neighborhood. So NULLs are justโ€ฆ not invited to the party. ๐Ÿ™ˆ

The -c flag and the weights parameter are mutually exclusive. Any use of the two together will produce an error. Periodt. ๐Ÿ’€

Differently-shaped neighborhood analysis windows can be achieved by using the weights= parameter to specify 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 โ€” effectively anti-aliasing the analysis mask. Iconic. โœจ

For aggregates where a weighted calculation isn't meaningful (specifically: minimum, maximum, diversity and interspersion), the weights are used to create a binary mask, where zero causes the cell to be ignored and any non-zero value causes the cell to be used.

r.neighbors copies the GRASS color files associated with the input raster map layer for those output map layers that are based on the neighborhood average, median, mode, minimum, and maximum. But because standard deviation, variance, diversity, and interspersion are indices, rather than direct correspondents to input values, no color files are copied for these map layers. (The user should note that although the color file is copied for average neighborhood function output, whether or not the color file makes sense for the output will be dependent on the input data values.)


๐ŸŽ€ Propagation of output precision ๐ŸŽ€

The following logic has been implemented: For any aggregate, there are two factors affecting 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 are: integer + no (integer input, unweighted), integer + yes (integer input, weighted), float + no (float input, unweighted), float + yes (float input, weighted):

  • average โ€” integer no โ†’ float, integer yes โ†’ float, float no โ†’ float, float yes โ†’ float
  • median โ€” integer no โ†’ [1], integer yes โ†’ [1], float no โ†’ float, float yes โ†’ float
  • mode โ€” integer no โ†’ integer, integer yes โ†’ integer, float no โ†’ [2], float yes โ†’ [2]
  • minimum โ€” integer no โ†’ integer, integer yes โ†’ integer, float no โ†’ float, float yes โ†’ float
  • maximum โ€” integer no โ†’ integer, integer yes โ†’ integer, float no โ†’ float, float yes โ†’ float
  • range โ€” integer no โ†’ integer, integer yes โ†’ integer, float no โ†’ float, float yes โ†’ float
  • stddev โ€” integer no โ†’ float, integer yes โ†’ float, float no โ†’ float, float yes โ†’ float
  • sum โ€” integer no โ†’ integer, integer yes โ†’ float, float no โ†’ float, float yes โ†’ float
  • count โ€” integer no โ†’ integer, integer yes โ†’ float, float no โ†’ integer, float yes โ†’ float
  • variance โ€” integer no โ†’ float, integer yes โ†’ float, float no โ†’ float, float yes โ†’ float
  • diversity โ€” integer no โ†’ integer, integer yes โ†’ integer, float no โ†’ integer, float yes โ†’ integer
  • interspersion โ€” integer no โ†’ integer, integer yes โ†’ integer, float no โ†’ integer, float yes โ†’ integer
  • quart1 โ€” integer no โ†’ [1], integer yes โ†’ [1], float no โ†’ float, float yes โ†’ float
  • quart3 โ€” integer no โ†’ [1], integer yes โ†’ [1], float no โ†’ float, float yes โ†’ float
  • perc90 โ€” integer no โ†’ [1], integer yes โ†’ [1], float no โ†’ float, float yes โ†’ float
  • quantile โ€” integer no โ†’ [1], integer yes โ†’ [1], float no โ†’ float, 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, the user 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 GIS 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 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)

Accessed: Saturday Jan 17 05:40:51 2026

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

ยฉ 2003-2025 GRASS Development Team, GRASS GIS 8.4.2 Reference Manual


and that's the whole page, bestie! ๐Ÿ’… this was GRASS 8.4.2, r.neighbors(1), last looked at Saturday Jan 17 05:40:51 2026. now go run some neighborhoods. ๐Ÿซถโœจ

๐Ÿ“ฆ where this page comes from