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

1

5

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.

Dyne answered 28/5, 2013 at 8:58 Comment(1)
if you can store your bitmap image in a png format you can use readPNG from png package otherwise you can use readbitmap package.Freewheel
A
7

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.

Anaplasty answered 28/5, 2013 at 9:22 Comment(2)
OK, so I started using read.bmp to try some of this out. I made a 16x16 image, and it's all black and white. I interpreted it through readPNG first (same image, but as a png file), and the values I got were all decimals under 1 (for the black pixels) or 1 for the white ones. When I saved the same image as a monochrome bmp, it wouldn't read it through read.bmp. Any ideas?Dyne
this is not good information for someone to help you, why not flesh out what you've done and what you expect in detail? See here for a guide: #5963769Anaplasty

© 2022 - 2024 — McMap. All rights reserved.