# Extract center coordinate polygon

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?

• Please add a little more information, and maybe some code to show what you have done. The "middle coordinate of an image" sounds like you want (xmin+xmax)/2, (ymin+ymax)/2 where xmin etc are the coordinates of the extent of the image. `gCentroid` works on polygons, not images. Do you want the centroid of a set of polygons? – Spacedman May 28 '18 at 8:45
• The help for `gCentroid` shows the computation of the centroids of two features at the same time (a triangle and a square) and the centroid of both, which you get by using `byid=FALSE`. How are you doing this? – Spacedman May 28 '18 at 8:50

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)
``````

``````### 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)
• This sounds like exactly what the answer is doing and doesn't explain why they get multiple centroid points, which is possibly because their polygons are more than one feature and they don't have `byid=FALSE` in the call to `gCentroid`. Or some other reason. Why not ask for more info? – Spacedman May 28 '18 at 8:52
``````x <- raster(system.file("external/test.grd", package="raster"))