Drawing Logos with R


I spent a rainy Sunday afternoon using Antonio S. Chinchón’s traveling salesperson approach to convert iconic logos into line drawings. When put to work on high contrast images, the method results yields some pretty cool textures.

Check out the gist and a few more images below:

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)
view raw tspDraw.R hosted with ❤ by GitHub