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.
- Default:
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 ๐
- Options:
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.
- Options:
weighting_factor=floatโ factor used in the selected weighting function (ignored fornoneandfile). so if you pickednoneorfile, 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 formethod=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.
- Options:
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 ๐ฅ
- Default:
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 case6). ๐ฏ
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 (notNULL) 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 is4.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 case64).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.neighborswill not align the output raster map layer with that of the input raster map layer. Ther.neighborsprogram 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.neighborswill 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:
- Whether the input map is integer or floating-point.
- 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 โfloatmedianโ integer no โ[1], integer yes โ[1], float no โfloat, float yes โfloatmodeโ integer no โinteger, integer yes โinteger, float no โ[2], float yes โ[2]minimumโ integer no โinteger, integer yes โinteger, float no โfloat, float yes โfloatmaximumโ integer no โinteger, integer yes โinteger, float no โfloat, float yes โfloatrangeโ integer no โinteger, integer yes โinteger, float no โfloat, float yes โfloatstddevโ integer no โfloat, integer yes โfloat, float no โfloat, float yes โfloatsumโ integer no โinteger, integer yes โfloat, float no โfloat, float yes โfloatcountโ integer no โinteger, integer yes โfloat, float no โinteger, float yes โfloatvarianceโ integer no โfloat, integer yes โfloat, float no โfloat, float yes โfloatdiversityโ integer no โinteger, integer yes โinteger, float no โinteger, float yes โintegerinterspersionโ integer no โinteger, integer yes โinteger, float no โinteger, float yes โintegerquart1โ integer no โ[1], integer yes โ[1], float no โfloat, float yes โfloatquart3โ integer no โ[1], integer yes โ[1], float no โfloat, float yes โfloatperc90โ integer no โ[1], integer yes โ[1], float no โfloat, float yes โfloatquantileโ 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:
- Output is always float:
average,variance,stddev, quantiles (with interpolation). - Output is always integer:
diversity,interspersion. - Output is integer if unweighted, float if weighted:
count. - Output matches input:
minimum,maximum,range,mode(subject to note 2 above), quantiles (without interpolation). - 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.regionr.clumpr.mapcalcr.mfilterr.statisticsr.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
- fedora 44: grass 8.4.2-4.fc44 ยท GPL-2.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms