R中多边形边上的采样点

R中多边形边上的采样点,r,gis,polygons,R,Gis,Polygons,如果在R中有一个空间多边形对象,如何生成位于该多边形边缘的一组n点 我原本以为可以从多边形顶点采样,但看起来有时会出现没有顶点的拉伸,因为多边形边是一条直线…假设要围绕周长绘制点,我会将其分为两部分: p(边e上的点p)=p(点p |边e)p(边e) p(边e)与其长度成正比。因此,首先采样一条边,然后采样一个点 在上面 下面是一个三角形示例: poly <- Polygon(list(x=c(1,2,3,1),y=c(1,2,1,1))) 一个简单的解决方案是使用包sf中的st_s

如果在R中有一个空间多边形对象,如何生成位于该多边形边缘的一组n点


我原本以为可以从多边形顶点采样,但看起来有时会出现没有顶点的拉伸,因为多边形边是一条直线…

假设要围绕周长绘制点,我会将其分为两部分:

p(边e上的点p)=p(点p |边e)p(边e)

p(边e)与其长度成正比。因此,首先采样一条边,然后采样一个点 在上面

下面是一个三角形示例:

  poly <- Polygon(list(x=c(1,2,3,1),y=c(1,2,1,1)))

一个简单的解决方案是使用包
sf
中的
st_segmentize()
,将点添加到直线上,然后沿着这些更细的点采样

st_segmentize()
有一个参数
dfMaxLength
,该参数定义了沿直线允许的最大距离。设置的值越小,点数就越多。它至少应与任意两点之间的最小距离一样小

library(sf)
library(tidyverse)

## original form
poly <- st_polygon(x=list(cbind(x=c(1,2,3,1),y=c(1,2,1,1))))

# segmentize, then convert to points
poly_points <- st_segmentize(poly, dfMaxLength = 0.1) %>% 
  st_coordinates() %>% 
  as.data.frame() %>% 
  select(X, Y) %>% 
  st_as_sf(coords = c("X", "Y"))

## plot: you can just use sample() now on your point dataset
plot(poly, reset = FALSE, main = "segmentize (black point), then sample 5 (red points)")
plot(poly_points, reset = FALSE, add = TRUE)
plot(poly_points[sample(1:nrow(poly_points), size = 5),], add = TRUE, col = 2, pch = 19)

这个代码示例有python版本吗?我不懂R语言
  e <- sample(nrow(dxy), 1, probs=h)
  u <- runif(1)
  p <- xy[e,] + u * dxy[e,]
  rPointOnPerimeter <- function(n, poly) {
    xy <- poly@coords
    dxy <- diff(xy)
    h <- hypot(dxy[,"x"], dxy[,"y"])

    e <- sample(nrow(dxy), n,replace=TRUE, prob=h)

    u <- runif(n)
    p <- xy[e,] + u * dxy[e,]

    p
  }
plot( rPointOnPerimeter(100,poly) )
library(sf)
library(tidyverse)

## original form
poly <- st_polygon(x=list(cbind(x=c(1,2,3,1),y=c(1,2,1,1))))

# segmentize, then convert to points
poly_points <- st_segmentize(poly, dfMaxLength = 0.1) %>% 
  st_coordinates() %>% 
  as.data.frame() %>% 
  select(X, Y) %>% 
  st_as_sf(coords = c("X", "Y"))

## plot: you can just use sample() now on your point dataset
plot(poly, reset = FALSE, main = "segmentize (black point), then sample 5 (red points)")
plot(poly_points, reset = FALSE, add = TRUE)
plot(poly_points[sample(1:nrow(poly_points), size = 5),], add = TRUE, col = 2, pch = 19)
 poly %>% 
  st_coordinates() %>% 
  as.data.frame() %>% 
  st_as_sf(coords = c("X", "Y")) %>% 
  st_distance() %>%  c() %>% 
  unique() %>% 
  sort