Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

Raster: Extract center of raster images and draw the border

$
0
0

I've like to extract coordinates of the center of 4 raster images in GEOTiff and draw the border of 2 selected images, for this I try:

library(raster)  
library(rgeos)

#create GeoTIFF raster
r <- raster(ncol=100, nrow=100)
s <- stack(lapply(1:3, function(i) setValues(r, runif(ncell(r)))))
f1 <- file.path(tempdir(), "sl1.tif")
writeRaster(s,f1, format="GTiff",datatype="FLT4S",overwrite=TRUE)

#crop in 4 sub-images
r2<-stack(raster("sl1.tif"))
SplitRas <- function(raster,ppside,save,plot){
  h        <- ceiling(ncol(raster)/ppside)
  v        <- ceiling(nrow(raster)/ppside)
  agg      <- aggregate(raster,fact=c(h,v))
  agg[]    <- 1:ncell(agg)
  agg_poly <- rasterToPolygons(agg)
  names(agg_poly) <- "polis"
  r_list <- list()
  for(i in 1:ncell(agg)){
    e1          <- extent(agg_poly[agg_poly$polis==i,])
    r_list[[i]] <- crop(raster,e1)
  }
  if(save==T){
    for(i in 1:length(r_list)){
      f1 <- file.path(tempdir(), paste0("sample_",i,sep=""))
      writeRaster(r_list[[i]], f1,
                  format="GTiff",datatype="FLT4S",overwrite=TRUE)
    }
  }
  if(plot==T){
    par(mfrow=c(ppside,ppside))
    for(i in 1:length(r_list)){
      plot(r_list[[i]],axes=F,legend=F,bty="n",box=FALSE)
    }
  }
  return(r_list)
}
splitRBG<-SplitRas(raster=r2,ppside=2,save=TRUE,plot=FALSE)
# 

#read the 4 images 
r.files <-list.files(tempdir(), pattern = "sample")
#[1] "sample_1.tif""sample_2.tif""sample_3.tif""sample_4.tif"

# get coordinates data from the center of each image
RES<-NULL
for(i in 1:length(r.files)){
value <- raster::extract(?????????) ## Here Im loosing for extract the center of each image
RES<-rbind(RES,cbind(r.files[i],coordinates(value))) #create a data frame of the results
}

First for I've like to create a data frame with this information

r.files         xcoord       ycooord      
sample_1.tif     -100         -50
sample_2.tif      50          -52
sample_3.tif      120          50
sample_4.tif      120         -30

Here my first problem, because I don't find I way to extract the center of each image before I expected:

#Finally draw a square with the images and points in center of coordinates only for sample_3 and sample_4
del<-c("sample_1.tif","sample_2.tif")
r.files2<-r.files [-del]
RES2<-RES[,-(1:2)]
image(r2)
for(i in 1:length(r.files2)){
e <- extent(r.files2[i])
pp <- rasterToPolygons(e, dissolve=TRUE) 
plot(pp, border='green') #Only countour color
points(RES2[i], col="red")
}

Any ideas ou more smart solution? Thanks


Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>