Search code examples
rggplot2jpeg

extracting hex colors form jpeg, store in data.frame, and then plotting with ggplot


Like the title says. I have an image that I want to extract the hex values for the color, store in a data.frame and then plot using ggplot.

Here's what I have:

library(ggplot2)
aws.logo = 'https://eventil.s3.amazonaws.com/uploads/group/avatar/8626/medium_highres_470196509.jpeg'

temp = tempfile()
download.file(aws.logo, temp, mode = 'wb')

## matrix of colors
y = jpeg::readJPEG(temp)
val <- rgb( y[,,1], y[,,2], y[,,3], maxColorValue = 255)
aws.img <- matrix(val, dim(y)[1], dim(y)[2])

out = reshape2::melt(aws.img)
names(out) = c('col', 'row', 'value')
out$value = as.character(out$value)

ggplot(out) + 
  geom_point(aes(x = row, y = -col), color = out$value) + ## why do I have to flip the order of 
  theme(legend.position="none")                           ## col after reshaping?

Why are the colors different from the logo on the website?


Solution

  • the raedJPEG will return RGB color values on the 0/1 scale, not the 0/255 scale. Use

    val <- rgb( y[,,1], y[,,2], y[,,3], maxColorValue = 1)
    

    Also, it's usually better not to have any $ operations in a ggplot call. Something like this would be safer

    ggplot(out) + 
      geom_point(aes(x = row, y = -col, color = value)) +       
      theme(legend.position="none") + 
      scale_color_identity ()
    

    enter image description here