2014-11-05 132 views
10

我有一個光柵棧,stk,在R.由三個光柵圖像下面是一個簡單的例子R:寫RasterStack和保留層名稱

# 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格式。

謝謝,凱文

+0

你在哪裏閱讀堆疊的tif文件? – 2014-11-06 23:31:30

+0

Paulo,感謝您的關注。我剛剛清理了這個例子,使其更加清晰並修正了一些措辭。我使用'stk < - stack(「myStack.tif」)'(最後一個代碼塊的第一行)讀入堆棧的tif文件。再次感謝。 – kguay 2014-11-07 18:52:10

回答

5

您可以使用本機光柵形式:

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

光柵網格格式由二進制.gri文件和.GRD頭文件。這將保留你的圖層名稱。但是請注意,.gri二進制文件不會被壓縮。

如果您需要在其他程序中打開柵格grd文件,您很可能需要編寫額外的頭文件。我通常使用ENVI頭格式來做到這一點。

hdr(myRaster, format = "ENVI") 

要從qgis打開文件,例如,您需要選擇.gri文件(二進制文件),它應該可以工作。

+0

感謝您的回答!在R中讀取柵格,圖層名稱將被保留。但是,QGIS無法顯示正確的圖層名稱,儘管它們正確存儲在.grd和.hdr文件中。有針對這個的解決方法嗎? – 2017-03-23 17:21:10

4

有點晚了,但可能幫助別人尋找可能的解決方案:

writeRaster(stk, filename=names(stk), bylayer=TRUE,format="GTiff") 
+0

這將按照OP的問題將每個圖層寫入單獨的文件,而不是將所有圖層和它們的名稱寫入一個堆棧。 – shekeine 2016-10-03 18:51:37

0

我寫我的文件,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 

/編輯 我剛剛注意到,當.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"