Skip to content

Commit

Permalink
First commit
Browse files Browse the repository at this point in the history
  • Loading branch information
aschinchon committed Apr 4, 2018
0 parents commit 6cc83e4
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .gitignore
@@ -0,0 +1,7 @@
.Rproj.user
.Rhistory
.RData
.Ruserdata
*.jpg
*.png
*.Rproj
34 changes: 34 additions & 0 deletions README.md
@@ -0,0 +1,34 @@
# The Travelling Salesman Portrait

After completing this experiment you will be able to create *one line drawing* from your favorite images. Resulting drawings are obtained using an algorithm to solve The Travelling Salesman Problem (TSP).

For example, if you load this image:

<img src="https://fronkonstin.com/wp-content/uploads/2018/04/frankenstein.jpg" height="400" align="middle">

The resulting portrait is this one:

<img src="https://fronkonstin.com/wp-content/uploads/2018/04/frankyTSP.png" height="400" align="middle">

## Getting Started

### Prerequisites

You will need to install the following packages (if you don't have them already):

```
install.packages("imager")
install.packages("dplyr")
install.packages("ggplot2")
install.packages("scales")
install.packages("TSP")
```

## More info

A complete explanation of the experiment can be found [at fronkonstin](https://fronkonstin.com/2018/04/04/the-travelling-salesman-portrait/)

## Authors

* **Antonio Sánchez Chinchón** - [@aschinchon](https://twitter.com/aschinchon)

46 changes: 46 additions & 0 deletions frankenstein_TSP.R
@@ -0,0 +1,46 @@
library(imager)
library(dplyr)
library(ggplot2)
library(scales)
library(TSP)

# Download the image
urlfile="http://ereaderbackgrounds.com/movies/bw/Frankenstein.jpg"

file="frankenstein.jpg"
if (!file.exists(file)) download.file(urlfile, destfile = file, mode = 'wb')

# Load, convert to grayscale, filter image (to convert it to bw) and sample
load.image(file) %>%
grayscale() %>%
threshold("45%") %>%
as.cimg() %>%
as.data.frame() %>%
sample_n(8000, weight=(1-value)) %>%
select(x,y) -> data

# Compute distances and solve TSP (it may take a minute)
as.TSP(dist(data)) %>%
solve_TSP(method = "arbitrary_insertion") %>%
as.integer() -> solution

# Create a dataframe with the output of TSP
data.frame(id=solution) %>%
mutate(order=row_number()) -> order

# Rearrange the original points according the TSP output
data %>%
mutate(id=row_number()) %>%
inner_join(order, by="id") %>% arrange(order) %>%
select(x,y) -> data_to_plot

# A little bit of ggplot to plot results
ggplot(data_to_plot, aes(x,y)) +
geom_path() +
scale_y_continuous(trans=reverse_trans())+
coord_fixed()+
theme_void()

# Do you like the result? Save it! (Change the filename if you want)
ggsave("frankyTSP.png", dpi=600, width = 4, height = 5)

0 comments on commit 6cc83e4

Please sign in to comment.