1

I have an image stored as matrix with grayscale for each pixel.

On this image I use SLIC algorithm to divide it into areas.

So I get a simple feature (sf) with polygons, I am able to extract in well-known-text (wkt).

But what I really need is a matrix/mask (same dimension as my pixel-image-matrix) storing the id of the polygon each pixel belongs to. For example the pixel image[1,2] belongs to polygon 5, then mask[1,2] <- 5.

I add some code to give example of my porblem (for a random "image"):

mat <- array(runif(10000, min=0, max=500), dim=c(100,100))
# SLIC  
library(supercells);
library(sf);
library(terra);
# make spatial raster from matrix
raster <- rast(mat);
rasterSLIC <- supercells(raster, k = 50, compactness = 1, dist_fun = "euclidean", avg_fun = "mean");
plot(raster);
plot(st_geometry(rasterSLIC), add = TRUE, lwd = 0.2);
point <- st_cast(rasterSLIC$geometry[2], to="POINT");
coord <- st_coordinates(point);

# what I want:
goal <- array(c(1,1,1,2,2,1,2,3,3), dim=c(3,3));
image(goal);
goal;

I would like to have something that helps me turning coords into such a mask/matrix I gave a small example for in goal.

Allerleirauh
  • 115
  • 3

1 Answers1

2

You can use terra::rasterize

Example data

library(terra)
# polygons
f <- system.file("ex/lux.shp", package="terra")
v <- vect(f)
# arbitrary raster
r <- rast(v, res=.01)

Solution:

rid <- rasterize(v, r, 1:nrow(r))

#or 
v$ID <- 1:nrow(v)
rid <- rasterize(v, r, "ID")

Illustration

plot(rid, type="classes")
text(v)
lines(v)

enter image description here

To get the a matrix of the raster values you can do

m <- as.matrix(rid, wide=TRUE)

With your more specific example, you could do

library(supercells);
library(terra)
set.seed(1)
mat <- array(runif(10000, min=0, max=500), dim=c(100,100))
r <- rast(mat)
SLIC <- supercells(r, k = 50, compactness = 1, dist_fun = "euclidean", avg_fun = "mean");
x <- rasterize(SLIC, r, "supercells")
xm <- as.matrix(x, wide=TRUE)

plot(x); 
s <- vect(SLIC)
lines(s)
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
  • For the OP's question, I guess the specific answer would be `goal <- rasterize(rasterSLIC, raster, "supercells")` – Allan Cameron Sep 17 '22 at 15:01
  • @RobertHijmans Thank you for the answer! It is a big step in the direction I need. But how do I get the matrix which seems to be the base for the plot? I need the 2D array with the ID of the polygon in each pixels position... I need `goal`, not `plot(goal)`, please! – Allerleirauh Sep 17 '22 at 17:41
  • 1
    you can use `as.matrix(x, wide=TRUE)`. See the expanded answer. – Robert Hijmans Sep 17 '22 at 21:36