[R] How to read in .jpeg files

Bill Simpson William.Simpson at drdc-rddc.gc.ca
Fri Feb 4 15:03:07 CET 2005


In case others are looking for a simple way to read in .jpeg files as 
ordinary matrices, here is my solution. I am only interested in greyscale 
images, so you will have to alter the following if you want colour.

Most .jpegs are colour, so first step is to open the file with ImageMagick 
"display" and save as greyscale.

Then convert (using IM "convert") .jpg to .pgm (grey scale):
convert -compress none groundhogbw.jpg groundhogbw.pgm
The "compress none" is needed to make it stored as plain, not raw .pgm

- using an ordinary editor you will see the top of the file is like this:
P2       # "magic number" identifies file as plain .pgm
350 383  # width, height
255      # max grey level
- the rest of the numbers are the grey levels left-right, top-bottom.
- use scan() to read file in as a vector, then use matrix() to convert to 
matrix

dims<-scan("groundhogbw.pgm",skip=1,nlines=1) #skip magic number and read dims
x<-matrix(scan("groundhogbw.pgm",skip=3),ncol=dims[2],nrow=dims[1])
for(i in 1:dims[1]) x[i,]<-rev(x[i,]) #flip the image vertically
image(x,col=gray(0:255/255),axes=F)

Bill




More information about the R-help mailing list