Search code examples
rmatrixrgbsimulate

Simulate a matricies of data using R as bands of satellite imagery from scratch


I am trying to 1) Simulate a matrix of data using R (in effect an image of numbers where each cell in the matrix has a number on the numerical scale of 0-255 (8 bit data))

2) Map the simulated data using mapping tools

3) Classify the image into 8-10 classes

The idea is to use a simple function to generate an image with 3 bands of Red Green and Blue imagery simulating multispectral imagery from satellite. So a composite of 3 different matricies. Like this.

Example

Then classify the composite by colour into 8 or 10 classes Any help would be much appreciated.


Solution

  • Based on your comments, here is an approach to sample as a gradient.

    imagerows <- 100
    imagecols <- 100
    cuts <- 8
    (imagecols * imagerows) %% cuts == 0 #Must be true
    colorgroups <- as.integer(cut(0:255,cuts))
    colors <- c("red","green","blue")
    result <- lapply(colors,function(y){
      unlist(
        lapply(seq(1,cuts),function(x){sample((0:255)[colorgroups == x],
                                      size = (imagerows*imagecols)/cuts,
                                      replace = TRUE)})
        )})
    

    result is now a list of length 3, each element of which is a 100x100 matrix. The matrix contains 100 * 100 random samples between 0 and 255, but in cuts number of increasing groups.

    We can then control the direction of the gradient using byrow = in matrix and by using rev() on the data.

    red.matrix <-   matrix((result[[1]]),nrow=imagerows,ncol=imagecols,byrow = TRUE)
    green.matrix <-   matrix((result[[2]]),nrow=imagerows,ncol=imagecols,byrow = FALSE)
    blue.matrix <-   matrix(rev(result[[3]]),nrow=imagerows,ncol=imagecols,byrow = FALSE)  
    

    Then we put the colors together with rgb() which outputs a vector. We can coerce it back into a matrix by assigning dimensions. Then just plot with grid.raster().

    library(grid)
    rgb.matrix <- rgb(red.matrix,green.matrix,blue.matrix,maxColorValue = 255)
    dim(rgb.matrix) <- c(imagerows,imagecols)
    grid.newpage()
    grid.raster(rgb.matrix,interpolate = FALSE)
    

    enter image description here