Need help converting a BMP image to a matrix in [R]?

后端 未结 1 835
猫巷女王i
猫巷女王i 2021-01-19 02:39

I\'m very new to R, and I was wondering if there was a simple way to convert a BMP image to a matrix in R. Mainly, I\'m looking for any package that can help. The values of

1条回答
  •  失恋的感觉
    2021-01-19 03:15

    A search for "bmp" on the CRAN packages list pulls up bmp and some others, for brevity I will just use this package.

    library(bmp)
    fl <- system.file("images", "5HT1bMARCM-F000001_seg001_lsm.bmp",  package = "bmp")
    b <- read.bmp(fl)
    

    This object is an array, with some information about the file:

     str(b)
     int [1:206, 1:206, 1:3] 107 111 119 123 115 119 119 139 143 143 ...
     - attr(*, "header")=List of 13
      ..$ filesize     : num 127774
      ..$ offset       : num 54
    

    It's a 3D array:

    dim(b)
    [1] 206 206   3
    

    There's an as.raster function, which takes an optional max argument:

    m <- as.raster(b, max = 255)
    

    This matrix m is now a 2D matrix of colours (hex).

    str(m)
     'raster' chr [1:206, 1:206] "#6B0303" "#6F0303" "#770303" ...
    
    
    dim(m)
    [1] 206 206
    

    Let's plot this thing, we need to set up a plot and then find out it's range so we can fill the device with our image.

    plot(1, type = "n", axes = FALSE, xlab = "", ylab = "")
    usr <- par("usr")
    rasterImage(m, usr[1], usr[3], usr[2], usr[4])
    

    Your needs will depend on the storage options used by your BMP file and on which software you use to read it.

    Basic image plot from R bmp package

    There are other options, with the readbitmap package and with rgdal (and perhaps that via raster), but it will depend on what you can install on your machine.

    0 讨论(0)
提交回复
热议问题