Rat*_*nil 4 r crop raster rgdal r-raster
我想使用提到的两个包"rgdal"和"raster"来裁剪GeoTiff光栅文件.一切都很好,除了产生的输出tif的质量非常差,灰度而不是颜色.原始数据是来自瑞士联邦地形办公室的高质量栅格地图,示例文件可以在这里下载.
这是我的代码:
## install.packages("rgdal")
## install.packages("raster")
library("rgdal")
library("raster")
tobecroped <- raster("C:/files/krel_1129_2012_254dpi_LZW.tif")
ex <- raster(xmn=648000, xmx=649000, ymn=224000, ymx=225000)
projection(ex) <- proj4string(tobecroped)
output <- "c:/files/output.tif"
crop(x = tobecroped, y = ex, filename = output)
Run Code Online (Sandbox Code Playgroud)
为了重现此示例,请下载示例数据并将其解压缩到文件夹"c:/ files /".奇怪的是,使用样本数据,图像质量可以正常,但仍然是灰度.
我使用"数据类型","格式"选项,但没有得到任何地方.任何人都能指出解决方案吗?我应该提供输入数据的更多信息吗?
编辑:Josh的例子非常适合样本数据2.不幸的是,我的数据似乎更老了,有些不同.如果您阅读以下GDALinfo,您能告诉我我选择了哪个选项:
# packages same as above
OldInFile = "C:/files/krel1111.tif"
dataType(raster(OldInFile)
[1] "INT1U"
GDALinfo(OldInFile)
rows 4800
columns 7000
bands 1
lower left origin.x 672500
lower left origin.y 230000
res.x 2.5
res.y 2.5
ysign -1
oblique.x 0
oblique.y 0
driver GTiff
projection +proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333+k_0=1 +x_0=600000+y_0=200000 +ellps=bessel +units=m+no_defs
file C:/files/krel1111.tif
apparent band summary:
GDType hasNoDataValue NoDataValue blockSize1 blockSize2
1 Byte FALSE 0 1 7000
apparent band statistics:
Bmin Bmax Bmean Bsd
1 0 255 NA NA
Metadata:
AREA_OR_POINT=Area
TIFFTAG_RESOLUTIONUNIT=2 (pixels/inch)
TIFFTAG_XRESOLUTION=254
TIFFTAG_YRESOLUTION=254
Warning message:
statistics not supported by this driver
Run Code Online (Sandbox Code Playgroud)
编辑(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)))
Run Code Online (Sandbox Code Playgroud)
看起来你需要改变两个细节.
首先,*.tif您正在阅读的文件有三个波段,因此应该在使用时阅读stack().(raster()在它上面使用只会读取单个波段(默认情况下是第一个),产生单色或"灰度"输出.
第二个(出于此处提到的原因)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)
Run Code Online (Sandbox Code Playgroud)
所有这些都输出以下tiff文件:
