digitalmaps
digitalmaps

Reputation: 2905

Plot a JPG image using base graphics in R

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?


Upvotes: 27

Views: 40481

Answers (6)

user3357177
user3357177

Reputation: 385

raster Has a built-in function for this called plotRGB

library(raster)  
myJPG <- stack("colourfulPic.jpg")  
plotRGB(myJPG)  

Upvotes: 0

James Hirschorn
James Hirschorn

Reputation: 7994

Using the imager package:

library(imager)

image <- load.image(image_filename)
plot(image)

This works for a number of image formats including jpeg, gif, etc...

Upvotes: 11

gregmacfarlane
gregmacfarlane

Reputation: 2283

If you are building an RMarkdown document, knitr::include_graphics() is direct and simple.

Upvotes: 4

Jealie
Jealie

Reputation: 6267

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!

Upvotes: 33

Apprentice Queue
Apprentice Queue

Reputation: 2036

Instead of rimage, perhaps use the package ReadImages:

library('ReadImages')
myjpg <- read.jpeg('E:/bigfoot.jpg')
plot(myjpg)

Upvotes: 6

user562529
user562529

Reputation: 951

Please note that ReadImages is now deprecated. Instead you could install the biOps package, which also contains a rich set of image manipulation methods. Use as follows:

library(jpeg)
library(biOps)

image <- readJPEG("test.jpg")

# image is of type imagedata (the red,green,blue channel images concatenated)

plot(image)

Edit: An object of type imagedata is accessed as image[Y,X,Channel], btw

Upvotes: -2

Related Questions