1

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?

  • 1
    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
3

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)

  • 1
    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
  • the first example solves the case! Thank you so much and for the very detailed answer! – Lucas May 28 '18 at 13:00
2

To compute the centre point of a raster, take the centre point of the X and Y extents.

x <- raster(system.file("external/test.grd", package="raster"))
c(xmax(x)+xmin(x), ymax(x)+ymin(x))/2

There's no need to convert the raster to a polygon and then run a centroid algorithm.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.