我想使用 bbox 或已知范圍裁剪柵格,即行和列中的 10 個像素。
您可以在下面看到一個可重現的示例:
library(terra)
r <- terra::set.ext(rast(volcano), terra::ext(0, nrow(volcano), 0, ncol(volcano)))
plot(r)
xmin <- xmin(r)
ymax <- ymax(r)
rs <- res(r)
n <- 10 # i.e. of rows and cols size
xmax <- xmin n * rs[1]
ymin <- ymax - n * rs[2]
x <- crop(r, c(xmin, xmax, ymin, ymax))
plot(x)

預期的回圈是:
- 完成所有柵格 (
r) 長度裁剪并將每個柵格片段臨時保存到 data.frame(或 data.table、raster、spatraster、list)
uj5u.com熱心網友回復:
了解更多關于您為什么要這樣做的背景資訊會很有用。如果您希望裁剪區域重疊,您的問題也不清楚;我假設你不希望那樣。
你可以這樣:
library(terra)
r <- rast(volcano)
n <- 10
獲取感興趣的起始單元格
rows <- seq(1, nrow(r), by=n)
cols <- seq(1, ncol(r), by=n)
cells <- cellFromRowColCombine(r, rows, cols)
獲取坐標
# upper-left coordinates of the starting cells
xy <- xyFromCell(r, cells)
rs <- res(r)
xy[,1] <- xy[,1] - rs[1]/2
xy[,2] <- xy[,2] rs[2]/2
# add the lower-right coordinates of the end cell
xy <- cbind(xy[,1], xy[,1] n*rs[1], xy[,2] - n*rs[2], xy[,2])
并回圈
x <- lapply(1:nrow(xy), function(i) {
crop(r, xy[i,])
})
核實
e <- lapply(x, \(i) ext(i) |> as.polygons()) |> vect()
plot(r)
lines(e, col="blue", lwd=2)

sapply(x, dim) |> t() |> head()
# [,1] [,2] [,3]
#[1,] 10 10 1
#[2,] 10 10 1
#[3,] 10 10 1
#[4,] 10 10 1
#[5,] 10 10 1
#[6,] 10 10 1
或者使用基于開始和結束單元編號的替代方法(為此,您需要 terra 1.5-25,目前您可以安裝的開發版本install.packages('terra', repos='https://rspatial.r-universe.dev'))
srows <- seq(1, nrow(r), by=n)
scols <- seq(1, ncol(r), by=n)
erows <- pmin(nrow(r), srows n-1)
ecols <- pmin(ncol(r), scols n-1)
scell <- cellFromRowColCombine(r, srows, scols)
ecell <- cellFromRowColCombine(r, erows, ecols)
cells <- cbind(scell, ecell)
x <- lapply(1:nrow(cells), function(i) {
e <- ext(r, cells[i,])
crop(r, e)
})
uj5u.com熱心網友回復:
通過您的方法使用terra我喜歡的資料:
library(terra)
r <- terra::set.ext(rast(volcano), terra::ext(0, nrow(volcano), 0, ncol(volcano)))
然后我們需要具有 4 個值 (xmin,xmax,ymin,ymax) 的范圍,[對于索引 {i,j,k,l}},我們想要從左上角到右上角遍歷柵格,然后再次下移,向下直到我們到達右下角[對于索引 {o,p}],然后進一步裁剪 [對于索引 {q}]。這是一個非常深的 for 回圈嵌套for,并且為了保持精神......最好做一些助手。
x_mtx <- matrix(c(seq(0,70,10), seq(10,80,10)), ncol = 2)
y_mtx <- matrix(c(seq(51, 1, -10), seq(61, 11, -10)), ncol = 2)
這些消除了索引 i:l,然后我們進行范圍:
crop_exts <- vector(mode = 'list', length= 48L)
for(p in 1:6){
for(o in 1:8){
crop_exts[[p]][[o]] <- ext(x_mtx[o, 1], x_mtx[o, 2], y_mtx[p, 1], y_mtx[p, 2])
}
}
# check our work
crop_exts[[1]][[1]] |> as.vector()
#xmin xmax ymin ymax
#0 10 51 61
crop_exts[[6]][[8]] |> as.vector()
#xmin xmax ymin ymax
# 70 80 1 11
看起來像從左上到右下。注意到 [[1]][[1]], [[6]][[8]],我們有第二個嵌套的 {p, o} 回圈如上所示,因為我們在這里使用索引來提取作物:
cropped_r <- vector(mode='list', length = 48L)# edit, establish outside `for`
for(p in 1:6){
for(o in 1:8){
cropped_r[[p]][[o]] <- crop(r, crop_exts[[p]][[o]])
}
}
plot(cropped_r[[1]][[1]])
plot(cropped_r[[6]][[8]])
總體而言,可能更容易的是生成完整的范圍矩陣,在這種情況下為 dim(48,4) ,但無法將我的頭繞在它周圍,并牢記索引,并保持我的精神......
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/456890.html
