是否有可能将(二进制)栅格数据直接传递给空间对象?

时间:2013-01-24 20:48:14

标签: r rcurl rgdal

我使用curl数据包的getBinaryURL从Web接收栅格数据(png,tiff,...)并将数据保存到磁盘。此栅格数据稍后用于空间分析,我目前使用栅格(和rgdal)数据包加载栅格数据并创建栅格对象。

library(RCurl)
url<-"http://demo.mapserver.org/cgi-bin/wms?version=1.1.1&service=WMS&request=GetMap&VERSION=1.1.1&LAYERS=continents&WIDTH=500&HEIGHT=500&BBOX=0,45,15,60&SRS=EPSG:4326&FORMAT=image/png"
map_png = getBinaryURL(url)
#saving the png to disk
map_file <- file("C:/Users/.../map.png", "wb")
writeBin(map_png, map_file)
close(map_file)

#loading png as raster
library(raster)
map <- raster("C:/Users/.../map.png")
#projection and extend
projection(map)<-"+proj=longlat +datum=WGS84 +ellps=WGS84 towgs84=0,0,0"
map@extent@xmin<-0
map@extent@xmax<-15
map@extent@ymin<-45
map@extent@ymax<-60

它有效,但原始数据的保存和加载部分并不是很好。所以我喜欢将“raw”(map_png)对象直接传递给“RasterLayer”(map)对象。像这样:

map <- raster(map_png)

任何人都知道如何归档这个?

-

我知道我可以解码png或使用数据包png进行解码,但是有很多不同的输入格式,这不是一种理想的方式。 更具体地说,我提供时间增益的示例,直接使用getBinaryURL()

获取后已经可用的二进制对象
system.time(
for(i in 1:200){
map_file <- file("C:/.../map.png", "wb")
writeBin(map_png, map_file)
close(map_file)
map <- raster("C:/.../map.png")
}
)

system.time(
for(i in 1:200){
xx <- readPNG(map_png)
map <- raster(xx[,,2])
}
)

1 个答案:

答案 0 :(得分:0)

用户, 你可以做一些事情。最好安装rgdalchange the mapserver format parameter on your call to a geographic format,例如GeoTIFF('Gtiff)。参数选项为here。这将保留地理配准。安装rgdal后,您可以非常轻松地阅读该文件:

url <- "http://demo.mapserver.org/cgi-bin/wms?version=1.1.1&service=WMS&request=GetMap&VERSION=1.1.1&LAYERS=continents&WIDTH=500&HEIGHT=500&BBOX=0,45,15,60&SRS=EPSG:4326&FORMAT=Gtiff"
download.file(url, destfile="my.tiff")
map <- brick("my.tiff")
map2 <- raster(map, layer=2)

map
class       : RasterBrick 
dimensions  : 500, 500, 250000, 3  (nrow, ncol, ncell, nlayers)
resolution  : 0.03, 0.03  (x, y)
extent      : 0, 15, 45, 60  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0 
data source : ~/my.tiff 
names       : my.1, my.2, my.3 
min values  :    0,    0,    0 
max values  :  255,  255,  255 

map2
class       : RasterLayer 
band        : 2 
dimensions  : 500, 500, 250000  (nrow, ncol, ncell)
resolution  : 0.03, 0.03  (x, y)
extent      : 0, 15, 45, 60  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0 
data source : ~/my.tiff 
names       : my.2 
values      : 0, 255  (min, max)

enter image description here

如果您想使用png格式,使用png包时会更容易:

library(png)
library(RCurl)
url <-"http://demo.mapserver.org/cgi-bin/wms?version=1.1.1&service=WMS&request=GetMap&VERSION=1.1.1&LAYERS=continents&WIDTH=500&HEIGHT=500&BBOX=0,45,15,60&SRS=EPSG:4326&FORMAT=image/png"
map_png <- getBinaryURL(url)
xx <- readPNG(map_png)
map <- raster(xx[,,2]) # The png is read as an array, and your data is in the second layer.