Skip to content

Instantly share code, notes, and snippets.

@jonocarroll
Last active March 11, 2016 14:10
Show Gist options
  • Save jonocarroll/7960dff5bf42e47423db to your computer and use it in GitHub Desktop.
Save jonocarroll/7960dff5bf42e47423db to your computer and use it in GitHub Desktop.
setwd("WORKINGDIRECTORY")
library(png) ## split .png into component matrices
library(RSAGA) ## grid.to.xyz, load before dplyr
library(dplyr) ## group_by(), summarise(), %>%
library(ggplot2) ## plotting
library(ggExtra) ## ggMarginal
## load the .png file
img <- png::readPNG("file10a566a2b4dc3.png")
## convert each channel into a data.frame
imgdf1 <- RSAGA::grid.to.xyz(img[,,1]) %>% mutate(col="red") # red channel
imgdf2 <- RSAGA::grid.to.xyz(img[,,2]) %>% mutate(col="green") # green channel
imgdf3 <- RSAGA::grid.to.xyz(img[,,3]) %>% mutate(col="blue") # blue channel
## collect these together to average
imgdf <- bind_rows(imgdf1, imgdf2, imgdf3)
## shift the coordinates to the correct values, and subtract the pixel values from 1 (white=0)
imgdf$x <- imgdf$x + 1
imgdf$y <- imgdf$y + 1
imgdf$z <- 1 - imgdf$z
## average the three channels (median) at each pixel
imgdf %<>% group_by(x, y) %>% summarise(z=median(z))
## plot the pixels, removing white pixels (z==0)
p <- ggplot(imgdf %>% filter(z!=0), aes(x=x, y=y)) + geom_point(size=0.1, pch=19) +
theme(panel.background=element_blank(),
line=element_blank(),
axis.text=element_blank(),
axis.title=element_blank(),
plot.margin=unit(c(0,0,0,0), "lines"),
complete=TRUE)
## add a marginal histogram of each pixel
ggExtra::ggMarginal(p, type="histogram", binwidth=1, col="darkturquoise")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment