TimColeman
TimColeman

Reputation: 21

Returning the 8 points directly adjacent to a point in a connected 2-D raster

I am currently working on code that will determine the connectivity of pixels within a raster image. I am currently having an issue with selecting all pixels within a minimum distance of a given pixel.

The goal of this line of code is to extract a subset from a matrix whose entries look like this:

             jcol      icol    valcol
300   0.005076142 0.8860759 0.0000000
27077 0.862944162 0.2911392 0.0000000
30604 0.974619289 0.4746835 0.0000000
3138  0.096446701 0.7341772 0.0000000
9926  0.314720812 0.4240506 0.0000000
27328 0.868020305 0.8734177 0.0000000
17624 0.558375635 0.8417722 0.0000000
13117 0.416243655 0.4936709 0.0000000
22622 0.720812183 0.2721519 0.6509804
15720 0.497461929 0.8670886 0.0000000

This where jcol is the relative y position, icol is the relative x position and valcol is the value of the raster at the pixel (x,y). This matrix covers the entire raster.

Currently I am attempting to use the subset function to go about this task:

P_N = subset(cluster.matrix, abs(cluster.matrix[,1]-x_N[,1]) == xthresh | abs(cluster.matrix[,2]-x_N[,2]) == ythresh)

Where xhtresh and ythresh represent the distance around the sample point x_N, a point which is chosen from the original (example below):

     jcol      icol    valcol 
3099    1 0.6518987 0.4862745

The issue is that I get the following output for P_N:

[1] jcol     icol     valcol
<0 rows> (or 0-length row.names)

Ideally, P_N would return the 8 points directly adjacent to x_N

I think my syntax in the subset function is wrong, especially because x_N is a 1x4 data entry, while cluster.matrix is a ~7000x4 matrix.

Upvotes: 1

Views: 875

Answers (1)

jbaums
jbaums

Reputation: 27388

I think you want raster::adjacent.

library(raster)
r <- raster(matrix(runif(100), 10))
cells <- adjacent(r, 34, 8, pairs=FALSE)
adj <- cbind(xyFromCell(r, cells), value=extract(r, cells))

Above, adjacent returns the cell numbers of the 8 cells adjacent to cell 34 of raster r. You can also pass a neighbourhood matrix that you might derive from a distance matrix/raster - see the help for argument directions at ?adjacent.

We then extract the x and y coordinates using xyFromCell, and the cell values with extract (alternatively we could just use r[cells]).

Upvotes: 2

Related Questions