我正在尝试平滑 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
,蓝色是平滑版本sp
,sps
。函数smooth
完成了这项工作,问题出在转换dd
为sp
兼容对象的某个地方。我怀疑问题是由raster()
但我不知道为什么或如何解决它。提前谢谢了。