我的项目工作流程的一部分需要从栅格创建轮廓。我能够使用
raster::rasterToContour
生成轮廓,并可以使用 R 中的 sf
包转换为多边形,但在获得所需结果时遇到一些困难。
这是我当前正在做的事情的缩小示例:
library(raster)
library(sf)
raster <- raster(matrix(c(rep(0,5),
0,1,1,1,0,
0,1,0,1,0,
0,1,1,1,0,
rep(0,5)), nrow = 5, ncol = 5))
plot(raster)
contour <- rasterToContour(raster, level = 0.5)
plot(contour, add = TRUE)
sf <- st_as_sf(contour) %>% st_polygonize()
plot(sf, col = "gray50", border = "black")
最初的似乎适合我的需要。然而,我似乎无法弄清楚如何避免中心区域被填满,如。我希望中心部分成为较大多边形中的一个洞,这样它看起来。我确信我可以通过将多边形拉入 GIS 软件来实现这一点,但在 R 中这样做会很有帮助。
你可以尝试用
st_cast("POLYGON")
代替st_polygonize()
:
library(raster)
#> Loading required package: sp
library(stars)
#> Loading required package: abind
#> Loading required package: sf
#> Linking to GEOS 3.11.2, GDAL 3.6.2, PROJ 9.2.0; sf_use_s2() is TRUE
library(sf)
m <- matrix(c(rep(0,5),
0,1,1,1,0,
0,1,0,1,0,
0,1,1,1,0,
rep(0,5)), nrow = 5, ncol = 5)
contour_1 <-
raster(m) |>
rasterToContour(level = 0.5) |>
st_as_sf() |>
st_cast("POLYGON")
contour_1
#> Simple feature collection with 1 feature and 1 field
#> Geometry type: POLYGON
#> Dimension: XY
#> Bounding box: xmin: 0.2 ymin: 0.2 xmax: 0.8 ymax: 0.8
#> CRS: NA
#> level geometry
#> C_1 0.5 POLYGON ((0.3 0.2, 0.2 0.3,...
plot(contour_1)
或者也许
stars
和stars::st_contour()
:
contour_2 <-
st_as_stars(m) |>
st_contour()
contour_2
#> Simple feature collection with 2 features and 3 fields
#> Geometry type: MULTIPOLYGON
#> Dimension: XY
#> Bounding box: xmin: 0 ymin: 0 xmax: 5 ymax: 5
#> CRS: NA
#> A1 Min Max geometry
#> 1 [-0.5,0.5) -0.5 0.5 MULTIPOLYGON (((4.5 5, 5 5,...
#> 2 [0.5,1.5) 0.5 1.5 MULTIPOLYGON (((4.000001 3....
plot(contour_2[,"A1"], key.pos = NULL)
创建于 2024-02-09,使用 reprex v2.1.0