Thursday, May 17, 2007

Convert image to matrix in R

This is how to use the Pixmap library to read in an image as a matrix.


> library(pixmap)
# the next command may only work on Linux
> system("convert foo.tiff foo.ppm")
> img <- read.pnm("foo.ppm")


To get info on your new object:

> str(img)

Although included in the previous output, the size of the image can be extracted by:

>img@size

Then to extract the red channel from the image for the first ten rows:

> myextract <- img@red[1:10,]

Or to extract the entire red channel to an actual matrix:

> red.mat<-matrix(NA,img@size[1],img@size[2])
> red.mat<-img@red

4 comments:

Kelsey said...

Hi, I know you wrote this a while ago but do you know of any way to do this on a non-Linux system? I have a jpeg I need to convert to a matrix in order to use the add.image function in fields.

If not, do you know of a way to convert a jpeg to a pnm or ppm? Then I could use the addlogo function in pixmap instead.

Thanks so much!!!

Forester said...

Hi Kelsey,

I only work in Linux these days, but the "convert" command is running ImageMagick which is available for Windows and Mac:

http://www.imagemagick.org/script/index.php

Kelsey said...

That just might work, I'm downloading it now. Thanks so much for your help!

Unknown said...

Hy, guys!

I had same 'problem' in Windows... I SOLVED IT using shell("convert foo.tiff foo.ppm") in place system("convert foo.tiff foo.ppm"). I hope it helps...

Hugs!