Junitar
Junitar

Reputation: 999

Invalid geometry after polygonizing rasters in R

I've a 1 arc-second SRTM raster layer from USGS.

I'm trying to turn that raster into a set of polygons for each 100 m elevational bands. I then would like to dissolve or union polygons of same attributes together.

My problem is that the majority of the polygons get an invalid geometry in the process.

I'm not sure where the problem arises so I will describe all the steps I did:

library(tidyverse)
library(sf)
library(stars)

# First I open the raster, remove NAs and set the min and max values
r <- raster::raster(my_raster)
raster::NAvalue(r) <- -1
r <- raster::setMinMax(r)

# Then I reclassify the raster in 100 m elevational bands
k <- 100
lv <- raster::minValue(r) %>% floor_nearest(100)
hv <- raster::maxValue(r) %>% floor_nearest(100)
s <- seq(lv, hv, k)

tibble(
  lower = s,
  higher = s + k,
  new = s
) %>% 
  raster::reclassify(r, ., right = FALSE) %>% 

  # Finally, I polygonize the reclassified raster and save the shapefile
  st_as_stars() %>% 
  st_as_sf(as_points = FALSE, merge = TRUE, connect8 = TRUE) %>% 
  st_write(dsn = "my_shapefile.shp")

The output of the above code looks like this:
enter image description here

However, if I check geometry validity in QGis, I end up with just a few valid polygons:
enter image description here

Q. What could be the reason of having so many polygons with an invalid geometry? What solution to fix it?

EDIT

Digging a bit more into the problem, I found this useful resource talking about the issue and different solutions to deal with it.
There is a specific function st_make_valid to fix invalid geometries in the lwgeom package, which is a dependency of the sf package since the version 0.4.

Upvotes: 0

Views: 595

Answers (1)

Brent Pease
Brent Pease

Reputation: 62

I think there are numerous causes of the problem...overlapping geometries, self-intersecting geoms, etc. Try buffering by a distance of 0 - not sure why this works but it’s a common solution on posts like this and it also worked for me when I was in your shoes.

Upvotes: 1

Related Questions