Skip to content
Prev 28438 / 29559 Next

Create pixels neighborhood in a raster

Dear Ben,

Sorry about of lot of mistakes, you are sure some part of code are 
confusing and/or with errors. I'll try again with some corrections:

First, I have the rasterization process of ants presence (0 is absence) 
in a 10x10 units raster:

#Packages
library(spatstat)
library(raster)

#Selection of ants data set
data(ants)
geo.form<-cbind(x=ants$x,y=ants$y)

#Definition of raster resolution - 10 units
ants.w<-as.owin(ants)
ext <- as(extent(c(ants.w$xrange,ants.w$yrange)), "SpatialPolygons")
ants.res<-rasterToPoints(raster(ext, resolution = 10), spatial = TRUE)
# coerce to SpatialPixelsDataFrame
gridded(ants.res) <- TRUE

#Rasterize
antscount<- rasterize(geo.form, raster(ants.res), fun='count', background=0)
values(antscount)[values(antscount) > 0] = 1

#Vizualize
plot(antscount)

Now, I'd like to create 1 pixels around each pixel of ant presence 
(Total of 9 pixels in each ant presence in antscount raster):

# For 1 pixel neighborhood
neigh1 <- matrix(1L, nrow=3, ncol=3); neigh1[2,2] <- 0L
ants1<-which(values(antscount)> 0)
cells<- xyFromCell(antscount, ants1)
e1<-adjacent(antscount, cells, directions=neigh1, pairs=FALSE)
ng_coords1 <- xyFromCell(antscount, e1)
points(ng_coords1, col="red")

I need that's this new create pixels has 1 as value too.

#Rasterize for 1 pixel neighborhood
antscount.9<- rasterize(ng_coords1 , raster(ants.res), fun='count', 
background=0)
plot(antscount.9)

The problem is my ng_coords1 coordinates is wrong and just only in the 
top of the antscount raster, despite xyFromCell(antscount, ants1) 
condition. My goal is a new ant presence raster with 8 pixels 
surrounding the neigourhood of each pixel (ant) in the original 
antscount raster.

Any ideas?

Thanks in advanced,

Alexandre