readPNG (png package)

readPNG(source)
Generate a matrix for a raster image from a PNG image. This is especially interesting since not only can this raster image be added to a plot, but the red-green-blue make-up (see rgb) of each pixel may be viewed in the output of readPNG. It is worth noting that functionality on the Windows platform may require some fussing (see the readPNG help file).
  • source – The file name of the PNG file as a character string. If necessary, include the path to the file.

Example. I import a simple PNG image that is a screen-capture of the pattern on the desktop of my computer, which I use as a background for the plot shown below. I hope to have a chance to discuss rasterImage sometime soon, but for now I’ve just used the function as needed in the code below.
> 
> #install.packages("png")
> library(png)
> 
> set.seed(5)
> N <- 100
> x <- runif(N)
> y <- 0.1*x+2.5*x^2-2*x^3 + rnorm(N,0,0.01)
> 
> img <- readPNG("pattern.png")
> img[1,1,] # rgb breakdown of top left pixel
[1] 0.5372549 0.6078431 0.6509804
> 
> png("png-package.png")
> plot(0, type='n', xlim=0:1, ylim=0:1,
+      main="Not the best use, but this gives the idea")
> rasterImage(img, -0.5, -0.3, 1.5, 1.3)
> points(x,y, col=rgb(0.8,0.4,0), pch=19)
> dev.off()
null device 
          1
> 

Leave a Reply