[GIS] Extract center coordinate polygon

coordinatespolygonr

I am new to R and I am looking for a little help. I have a polygonized raster image and I want to get the middle coordinate of the image. I have tried gCentroid
but there I get a list of multiple coordinates… how do I get just the middle one?

Best Answer

You can convert your raster to polygon then use gCentroid to extract the centroid. Here is an example taken from this answer

library(raster)
library(rgeos)

# example data
x <- raster(system.file("external/test.grd", package="raster"))

### To get the rectangular extent
e <- extent(x)
# coerce to a SpatialPolygons object
p <- as(e, 'SpatialPolygons')  

# calculate the centroid 
c1 <- gCentroid(p)
plot(p)
plot(c1, col='blue', add=TRUE)

### To get a polygon that surrounds cells that are not NA
# make all values the same. Either do
r = x > -Inf
# or alternatively
# r = reclassify(x, cbind(-Inf, Inf, 1))

pp <- rasterToPolygons(r, dissolve=TRUE)

# calculate the centroid 
c2 <- gCentroid(pp)

# look at the results
plot(x)
plot(p,  lwd=5, border='blue',  add=TRUE)
plot(c1, col='blue', add=TRUE)
plot(pp, lwd=3, border='red', add=TRUE)
plot(c2, col='red',  add=TRUE, pch = 17)

Related Question