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

巧了我就是萌 提交于 2020-01-21 11:43:09

问题


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 each element in the matrix would correspond to colors.


回答1:


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.

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.



来源:https://stackoverflow.com/questions/16787894/need-help-converting-a-bmp-image-to-a-matrix-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!