编辑(2015-03-10):
如果只是想裁剪掉现有 GeoTIFF 的子集并将裁剪后的部分保存到新的*.tif
文件,使用gdalUtils::gdal_translate()
可能是最直接的解决方案:
library(raster) # For extent(), xmin(), ymax(), et al.
library(gdalUtils) # For gdal_translate()
inFile <- "C:/files/krel_1129_2012_254dpi_LZW.tif"
outFile <- "subset.tif"
ex <- extent(c(686040.1, 689715.9, 238156.3, 241774.2))
gdal_translate(inFile, outFile,
projwin=c(xmin(ex), ymax(ex), xmax(ex), ymin(ex)))
看来您需要更改两个细节。
首先,*.tif
您正在读取的文件有三个波段,因此应该使用以下方式读取stack()
。 (使用raster()
它只会读取单个波段(默认情况下是第一个波段),产生单色或“灰度”输出。
Second (由于这里提到的原因 https://stat.ethz.ch/pipermail/r-sig-geo/2014-August/021624.html) writeRaster()
默认情况下会将值写为实数(Float64
在我的机器上)。要明确告诉它您想使用字节,请给它参数datatype='INT1U'
.
library("rgdal")
library("raster")
inFile <- "C:/files/krel_1129_2012_254dpi_LZW.tif"
outFile <- "out.tif"
## Have a look at the format of your input file to:
## (1) Learn that it contains three bands (so should be read in as a RasterStack)
## (2) Contains values written as Bytes (so you should write output with datatype='INT1U')
GDALinfo(inFile)
## Read in as three separate layers (red, green, blue)
s <- stack(inFile)
## Crop the RasterStack to the desired extent
ex <- raster(xmn=648000, xmx=649000, ymn=224000, ymx=225000)
projection(ex) <- proj4string(s)
s2 <- crop(s, ex)
## Write it out as a GTiff, using Bytes
writeRaster(s2, outFile, format="GTiff", datatype='INT1U', overwrite=TRUE)
所有这些都输出以下 tiff 文件: