Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot a JPG image using base graphics in R

Tags:

I am searching for a simple way to plot a photographic JPEG image on a graphics device in R.

For example the following using the raster package appears to ignore the colour attributes in the image. I want to reproduce the photograph in its original colours:

library(raster) library(rgdal)  myJPG <- raster("colourfulPic.jpg") plot(myJPG)  ## Recolours JPEG; 

I have discovered that the package rimage has recently been archived and appears to no longer be recommended for use (see here), if it, indeed, ever did what I need.

Similarly the EBImage for BioConductor, which may also possibly work, is not built for 64 bit Windows, and unfortunately I need this architecture.

Please tell me I missing something very obvious in base graphics?


like image 564
digitalmaps Avatar asked Mar 03 '12 04:03

digitalmaps


People also ask

How do I insert an image into a plot in R?

To add a picture to a plot in base R, we first need to read the picture in the appropriate format and then rasterImage function can be used. The most commonly used format for picture in R is PNG. A picture in PNG format can be added to a plot by supplying the values in the plot where we want to add the picture.

How do I save a figure as a JPEG in R?

Plots panel –> Export –> Save as Image or Save as PDF Specify files to save your image using a function such as jpeg(), png(), svg() or pdf(). Additional argument indicating the width and the height of the image can be also used.

What does null device mean in R?

There is a "null device" which is always open but is really a placeholder: any attempt to use it will open a new device specified by getOption("device") . Devices are associated with a name (e.g., "X11" or "postscript" ) and a number in the range 1 to 63; the "null device" is always device 1.


1 Answers

Here goes an updated solution, that relies only on the jpeg package and handles color and greyscale images (packages used in other solutions are outdated and won't install with a recent R version).

The solution consists in this plot function:

plot_jpeg = function(path, add=FALSE) {   require('jpeg')   jpg = readJPEG(path, native=T) # read the file   res = dim(jpg)[2:1] # get the resolution, [x, y]   if (!add) # initialize an empty plot area if add==FALSE     plot(1,1,xlim=c(1,res[1]),ylim=c(1,res[2]),asp=1,type='n',xaxs='i',yaxs='i',xaxt='n',yaxt='n',xlab='',ylab='',bty='n')   rasterImage(jpg,1,1,res[1],res[2]) } 

This function can then be called with the path of the picture as argument, for example:

plot_jpeg('~/nyancat.jpg') 

To add the picture to an existing plot, use the switch add=TRUE - and be wary of axis limits!

like image 73
Jealie Avatar answered Oct 21 '22 13:10

Jealie