3

Has anyone found a solution for turning polygons into centrelines using R? It has to be in R as I'm deploying it in parallel on a UNIX cluster. I've got as far as:

library(sf)    
centreline <- st_cast(polygon$geometry, "LINESTRING")

But this outputs the entire polygon boundary rather than the centreline.

Here are two solutions in ArcGIS and QGIS.

Creating Centrelines from Road Polygons/Casings using ArcGIS Desktop?

Finding centrelines from polygons in QGIS?

Sample data and code of what I've already tried:

Data

library(sf)
library(dplyr)

# inputs
linepath <- 'river.shp'
pointpath <- 'river_point.shp'
epsg <- 27700 

line <- st_read(dsn = linepath) %>% st_transform(epsg)

point <- st_read(dsn = pointpath) %>% st_transform(epsg)

# Buffer point 
bufferpoint <- st_buffer(point, dist = 1)  %>%
  st_transform(epsg) 

# Cut line with point
# A helper function that erases all of y from x:
st_erase = function(x, y) st_difference(x, st_union(st_combine(y))) 

splitline <- st_erase(line, bufferpoint) %>% 
  mutate(id = as.factor(row_number()))

buffered <- st_buffer(splitline, dist = 0.5) 

dissolved <- st_union(buffered) %>% as('Spatial') %>% st_as_sf()

singlepart <- st_cast(dissolved, 'POLYGON') %>%
  mutate(id = as.factor(row_number()))

centreline <- st_cast(singlepart$geometry, "LINESTRING")
Josh J
  • 191
  • 6
  • This is a duplicate of a question I answered on Stack OVerflow: https://stackoverflow.com/questions/9595117/identify-a-linear-feature-on-a-raster-map-and-return-a-linear-shape-object-using/9643004#9643004 - that was designed with sp spatial classes but its trivial to convert to that. – Spacedman Jul 02 '19 at 22:05
  • Thanks, but unfortunately my data relates to river polygons and your method (which is great) doesn't work at intersections. – Josh J Jul 03 '19 at 12:07
  • A picture of your data (or a sample of it) would be very useful. – Spacedman Jul 03 '19 at 13:46
  • Please don't use library(tidyverse), try and only include packages that you use rather than pulling in an entire universe. At first glance it looks like dplyr is the only thing needed. – Spacedman Jul 03 '19 at 14:13
  • Take a look at the cmgo package. It has CM.calculateCenterline function. https://github.com/AntoniusGolly/cmgo – Anatolii Apr 06 '20 at 09:45

0 Answers0