24

我有一个光栅堆栈,stk由 R 中的三个光栅图像组成。这是一个简单的例子

# set up a raster stack with three layers
> library(raster)
> r <- raster(nrows=10,ncols=10)
> r[] <- rnorm(100)
> stk <- stack(r,r,r)

# layer names are set by default
> names(stk)
[1] "layer.1" "layer.2" "layer.3"

我为栅格图层指定名称:

# set layer names to "one", "two" and "three"
> names(stk) <- c('one','two','three')

> names(stk)
[1] "one" "two" "three"

当我使用以下命令将 RasterStack 写入 GeoTiff(多层)时:

writeRaster(stk,"myStack.tif", format="GTiff")

图层根据文件名重命名(见> names(stk)下文)。

当我在光栅堆栈中阅读时:

> stk <- stack("myStack.tif")

# the layer names have been set automatically based on the filename
# they should be "one", "two" and "three"
> names(stk)
[1] "myStack.1" "myStack.2" "myStack.3"

在 R 中编写 RasterStacks 时,您知道有什么方法可以保留图层名称吗?我尝试将堆栈写入 GeoTIFF 和 NetCDF 格式。

谢谢,凯文

4

4 回答 4

11

您可以使用本机光栅格式:

myRaster <- writeRaster(stk,"myStack.grd", format="raster")

光栅网格格式由二进制 .gri 文件和 .grd 头文件组成。这将保留您的图层名称。但是请注意,.gri 二进制文件未压缩。

如果您需要在其他程序中打开光栅 grd 文件,您很可能需要编写一个额外的头文件。我通常使用 ENVI 标头格式来做到这一点。

hdr(myRaster, format = "ENVI")

例如,要从 qgis 打开文件,您将选择 .gri 文件(二进制文件),它应该可以工作。

于 2014-11-29T12:20:02.077 回答
11

有点晚了,但可能会帮助其他人寻找可能的解决方案:

writeRaster(stk, filename=names(stk), bylayer=TRUE,format="GTiff")
于 2014-12-18T13:14:36.810 回答
3

您可以使用terrastars

使用土地

如果您将堆栈转换为rast对象,则名称将被保留,从terra

然后您可以使用 raster::writeRaster 或 terra::writeRaster,无论哪种方式,名称都会保留!

library(terra)
x <- rast(stk)
terra::writeRaster(x, "file.tif")
y <- raster::brick("file.tif") 
#y <- terra::rast("file.tif")
#y <- stars::read_stars("file.tif")
names(y)

使用星星

library(stars)
x <- st_as_stars(stk)
write_stars(x, "file2.tif")
y <- raster::brick("file2.tif")
#y <- terra::rast("file2.tif")
#y <- stars::read_stars("file2.tif")
names(y)
于 2021-09-29T23:14:00.007 回答
1

我将我的文件编写为 ENVI 文件,并更改了 ENVI 头文件中的波段名称。现在可以在 ENVI 和 ArcGis 中打开这些文件,并保留图层名称。

#write ENVI file (.envi; .hdr; .envi.aux.xml) with automatic layer names
writeRaster(stk, "myStack" , format="ENVI")

#change layer names in ENVI header (.hdr):
n="myStack.hdr"  
x <- readLines(n)
x <- gsub("Band 1,", "one,", x) 
x <- gsub("Band 2,", "two," , x)
x <- gsub("Band 3", "three", x)  
cat(x, file=n, sep="\n") #overwrites the old ENVI header

/edit 我刚刚注意到,当 .envi 文件重新导入 R 时,图层名称会再次被删除。SAGA中的同样问题。

image <- stack("myStack.envi")  
names(image)
#[1] "myStack.1" "myStack.2" "myStack.3"

image = readGDAL("myStack.envi") 
names(image)
#[1] "band1" "band2" "band3"
于 2015-08-31T12:50:01.067 回答