I have polygon image as png file. I changed this png polygon to spatialPolygon in R.

However, when I extract the cells within the spatialpolygon, only cells within the contour are filtered, not within the polygon itself.

The reason I guess is that the spatialpolygon contour has the width, so only cells within the contour are obtained.

How can I fix this situation?

Spatialpolygon

Filetered cells

# Load PNG image
img <- readPNG("../polygon.png")

# Convert image to grayscale if it's color (assuming RGB color here)
if (dim(img)[3] == 3) {
  img <- 0.299*img[,,1] + 0.587*img[,,2] + 0.114*img[,,3]
}

# Convert to matrix
img <- matrix(img, nrow = dim(img)[1], ncol = dim(img)[2])

# Create a raster from the matrix
r <- raster(img)

# Set the extent of the raster based on your corner points
xmin <- min(11810, 12230, 12350, 12220) # smallest x-coordinate
xmax <- max(11810, 12230, 12350, 12220) # largest x-coordinate
ymin <- min(53440, 53290, 53420, 53540) # smallest y-coordinate
ymax <- max(53440, 53290, 53420, 53540) # largest y-coordinate

extent(r) <- c(xmin, xmax, ymin, ymax)

spat_pol <- rasterToPolygons(r, fun=function(x){x == 1})
0

There are 0 best solutions below