不规则多边形的栅格化坐标会改变原始形状

Rasterizing coordinates for an irregular polygon changes original shape

我试图在 R 中平滑不规则多边形的边缘,即将其尖角变成圆边。我正在尝试使用 smoothr::smooth 来执行此操作,但此函数对包 sfsp 中的对象进行操作,而我只有一组坐标。不知何故,将我的 data.frame 变成 SpatialPolygonsDataFrame 对象(包 sp 中的对象 class)的结果是一个矩形,其边界是原始多边形的极限。有谁知道如何在保持原始多边形形状的同时将我的一组坐标转换为 class 与 smoothr::smooth 兼容的对象?这是我所做的,部分遵循 this 页面上的说明:

rm(list=ls()) # my compulsive habit of making sure R's memory is a clean slate

# Example dataset:
dd <- data.frame(
        Lon = c(18.95379, 18.82409, 18.58987, 18.80541, 18.92427, 19.00264),
        Lat = c(-32.42492, -32.32498, -31.89642, -31.73606, -32.16217, -32.37052)
        )

plot(0,0,
    xlim=c(18.5,19.1), ylim=c(-32.5,-31.6), 
    xlab="Longitude", ylab="Latitude"
    )
polygon(dd[,"Lon"],dd[,"Lat"], border="red")

# To make it smooth I plan on using
library(smoothr)
# But smoothr:: smooth works on objects from packages sf or sp so I need to  convert dd.
#convert to spatial points
library(sp)
coordinates(dd) = ~Lon + Lat
# convert to raster
library(raster)
rr <- raster::raster(dd)
#convert raster to polygons
sp = rasterToPolygons(rr, dissolve = T)
map(sp, add=T, col="green", fill=F)
# somehow my irregular polygon turned into a rectangle.
sps <- smooth(sp, method = "ksmooth", smoothness=5)
# this works, but of course is only rounding the corners of sp
map(sps, add=T, col="blue", fill=F)

红色是我来自 data.frame dd 的原始多边形,绿色是对象 sp,蓝色是 spsps 的平滑版本。函数 smooth 完成了这项工作,问题出在将 dd 转换为 sp 兼容对象的某个地方。我怀疑问题是由 raster() 引起的,但我不确定为什么或如何解决它。 非常感谢。

这里我使用了sf,因为我个人觉得这样更容易:

library(sf)
library(smoothr)

# Example dataset:
dd <- data.frame(
  Lon = c(18.95379, 18.82409, 18.58987, 18.80541, 18.92427, 19.00264),
  Lat = c(-32.42492, -32.32498, -31.89642, -31.73606, -32.16217, -32.37052)
)

# cast to polygon, use multipoint first though.   
polygon <- as.matrix(dd) %>%
  sf::st_multipoint() %>%
  sf::st_cast("POLYGON")

#  smooth polygon
polygon_smoothed <- smoothr::smooth(polygon, method = "ksmooth", smoothness = 0.5)

# plot to check
plot(polygon, col = "red")
plot(polygon_smoothed, col = "blue", add = T)

我在这里找到了另一个解决方案:https://rstudio-pubs-static.s3.amazonaws.com/202536_7a122ff56e9f4062b6b012d9921afd80.html

# Example dataset:
dd <- data.frame(
        Lon = c(18.95379, 18.82409, 18.58987, 18.80541, 18.92427, 19.00264),
        Lat = c(-32.42492, -32.32498, -31.89642, -31.73606, -32.16217, -32.37052)
        )       
plot(0,0,
    xlim=c(18.5,19.1), ylim=c(-32.5,-31.6), 
    xlab="Longitude", ylab="Latitude"
    )
polygon(dd[,"Lon"],dd[,"Lat"], border="red")

library(sp)
p = Polygon(dd)
p2 = Polygons(list(p),1) # I believe this aggregates polygons, so in this case it doesn't do anything.
sp = SpatialPolygons(list(p2))
sps <- smooth(sp, method = "ksmooth", smoothness=0.7)
plot(sps, add=T, border="blue")