0

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

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完成了这项工作,问题出在转换ddsp兼容对象的某个地方。我怀疑问题是由raster()但我不知道为什么或如何解决它。提前谢谢了。

4

2 回答 2

1

我在这里找到了另一个解决方案: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")
于 2019-08-01T10:00:41.680 回答
1

我在这里使用过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)

于 2019-08-01T09:42:55.440 回答