Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 279
riders994 Avatar asked May 28 '13 08:05

riders994


1 Answers

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.

like image 100
mdsumner Avatar answered Oct 02 '22 21:10

mdsumner