Skip to content

Instantly share code, notes, and snippets.

@etachov
Last active April 8, 2018 23:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save etachov/1ef225e3824486ca039cc0ccf4511702 to your computer and use it in GitHub Desktop.
Save etachov/1ef225e3824486ca039cc0ccf4511702 to your computer and use it in GitHub Desktop.
Use @aschinchon's traveling salesperson approach to turn iconic logos into line drawings
library(imager)
library(dplyr)
library(ggplot2)
library(scales)
library(TSP)
## this function takes a 3 channel image and turns it into a line drawing
# internals of the function are all from here https://github.com/aschinchon/travelling-salesman-portrait
tspDraw <- function(raw_img, point_sample_size, line_color, back_color) {
# load the image and get started
# more background on how imager works here https://dahtah.github.io/imager/imager.html
raw_img <- load.image(raw_img)
# get the sample points
data <- raw_img %>%
grayscale() %>%
as.cimg() %>%
as.data.frame() %>%
# adjust the point_sample_size variable to adjust the texture of the tsp image
# smaller sample looks jagged, large sample looks smooth
sample_n(size = point_sample_size, weight = (1 - value)) %>%
select(x, y)
# solve the tsp problem and return a data.frame with the values
solution <- as.TSP(dist(data)) %>%
solve_TSP(method = "arbitrary_insertion") %>%
as.integer()
order <- data.frame(id = solution) %>%
mutate(order = row_number())
# join the tsp solution
data_to_plot <- data %>%
mutate(id = row_number()) %>%
inner_join(order, by = "id") %>%
arrange(order) %>%
select(x, y)
p <- ggplot(data_to_plot, aes(x, y)) +
geom_path(color = line_color) +
scale_y_continuous(trans=reverse_trans())+
coord_fixed() +
theme_void() +
theme(plot.background = element_rect(fill = back_color))
return(p)
}
## draw the logo images
# gucci gucci gucci
gucci <- tspDraw(raw_img = "gucci_logo.jpg",
point_sample_size = 7000,
line_color = "white",
back_color = "black")
ggsave("gucci_tsp.jpg", gucci)
# panda panda panda aka WWF
wwf <- tspDraw(raw_img = "wwf_logo.jpg",
# sample a few more points to give the font enough detail
point_sample_size = 8000,
line_color = "white",
back_color = "black")
ggsave("wwf_tsp.jpg", wwf)
# mercedes
mercedes <- tspDraw(raw_img = "mercedes_logo.jpg",
# pump this up to 12K to get capture the text and leaf detail
point_sample_size = 12000,
line_color = "white",
back_color = "black")
ggsave("mercedes_tsp.jpg", mercedes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment