Search code examples
rgisspatialraster

Why rasterToPolygons is creating horizontal lines?


I am trying to transform a raster layer to polygons based on its values. My raster looks like this:

enter image description here

> labels_rast
class       : RasterLayer 
dimensions  : 26, 64, 1664  (nrow, ncol, ncell)
resolution  : 0.03000146, 0.02999809  (x, y)
extent      : 352032, 352033.9, 8551454, 8551455  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=18 +south +datum=WGS84 +units=m +no_defs+ellps=WGS84 +towgs84=0,0,0 
data source : in memory
names       : layer 
values      : 1, 3  (min, max)

When I apply the rasterToPolygons function (dissolve = TRUE), I get extra polygons (defined by horizontal lines):

enter image description here

How can I avoid the creation of the polygons defined by the horizontal lines?


Solution

  • It works for this very similar case:

    library(raster)
    r <- raster(nrow=26, ncol=64, xmn=352032, xmx=352033.9, ymn=8551454, ymx=8551455, crs="+proj=utm +zone=18 +south +datum=WGS84 +units=m", vals=3)
    r[, 20:40] <- 2
    r[1:3, 1:60] <- 1
    r[24:26, 5:64] <- 1
    x <- rasterToPolygons(r, dissolve=TRUE)
    plot(r)
    lines(x)
    

    I am guessing that it does not work for you because of floating point imprecision. Would have to see your file to be sure. But, if so, perhaps you can round the extent (or resolution) a little bit.

    For example

    res(labels_rast) <- 0.03 
    y <- rasterToPolygons(labels_rast, dissolve=TRUE)