Search code examples
rrasterr-raster

How to get lat/long of the center pixel in a raster image in R?


I want to extract the Latitude and Longitude information of the pixel that is in the center of a raster image. If the raster image is not exactly square (e.g. it is not 50x50), I want to get the lat/long of approximately the center pixel. Here is some reproducible data:

library(raster)
r = raster(ncol=25, nrow=25, xmn=-1000, xmx=1000, ymn=-100, ymx=900, vals = 1:(25*25))
crs(r) = crs(raster())

Solution

  • Here is an approach to get the center of the central grid cell

    library(raster)
    r <- raster(ncol=25, nrow=25, xmn=-1000, xmx=1000, ymn=-100, ymx=900)
    
    row <- trunc(nrow(r)/2)
    col <- trunc(ncol(r)/2)
    c(row, col)
    #[1] 12 12
    cell <- cellFromRowCol(r, row, col)
    cell
    #[1] 287
    xyFromCell(r, cell)
    #       x   y
    #[1,] -80 440
    

    Another way could be to get the center of the raster and the grid cell that it falls in

    x <- xmin(r) + (xmax(r) - xmin(r))/2
    y <- ymin(r) + (ymax(r) - ymin(r))/2
    cell <- cellFromXY(r, cbind(x,y))
    cell
    #313
    rowColFromCell(r, cell)
    #     row col
    #[1,]  13  13
    xyFromCell(r, cell)
    #     x   y
    #[1,] 0 400
    

    The difference here is because the number or rows and columns is even, so you can take c(12, 12) or c(13, 13) or some other variation of 12 and 13.