Pixelating images in R


Hadley Wickham started some banter on Twitter the other day by challenging folks to pixelate a meme using ggplot.

I thought I’d give it a try with some water-related images. Using the imager and ggplot libraries:

# load a random picture of Hoover Dam
hoover_jpg <- load.image("https://lvspydertours.com/images/hd-1.jpg")

# plot it using ggplot
ggplot(data.frame()) +  # just insert a blank data frame or tibble
  annotation_custom(g = grid::rasterGrob(hoover_jpg, interpolate=TRUE)) +
  theme_void()

Now I’m gonna pixelate it.

# resize to pixelate
hoover <- resize(hoover_jpg,
                 round(width(hoover_jpg)/10),
                 round(height(hoover_jpg)/10))

# plot
ggplot(data.frame()) +
  annotation_custom(g = grid::rasterGrob(hoover, interpolate=TRUE)) +
  theme_void()

How about the Amazon?

Cannon Beach, Oregon. (you recognize it from the final scene of The Goonies)