Skip to content

Instantly share code, notes, and snippets.

@chichacha
Created March 16, 2020 05:56
Show Gist options
  • Save chichacha/77fc0eb36fc7e47cc8dd597532307fb0 to your computer and use it in GitHub Desktop.
Save chichacha/77fc0eb36fc7e47cc8dd597532307fb0 to your computer and use it in GitHub Desktop.
Image + K means clustering + Convex Hull
library(magick)
library(imager)
library(tidyverse)
create_pebble_art <- function(img_url,cluster_cnt=500,samp=10000){
img <- image_read(img_url)
## convert image to df
im.df.colour <- img %>%
image_resize(400)%>%
image_quantize() %>%
magick2cimg() %>%
as.data.frame(wide="c") %>% ## so that rgb value is in separate column.
mutate(hex=rgb(c.1,c.2,c.3))
## original image is too big, so sample them...
im.df.mini <- im.df.colour %>%
sample_n(size=samp)
## run K-means so that group is formed on distance and colour
k_res <-im.df.mini %>% select_if(is.numeric) %>% kmeans(centers=cluster_cnt)
im.df.mini$grp = k_res$cluster
im_simp <-im.df.mini %>%
select(x,y,grp) %>%
group_by(grp) %>%
nest() %>%
mutate(hull=map(data,chull)) %>%
mutate(out=map2(data,hull,~.x[.y,])) %>%
unnest(out) %>%
left_join(im.df.colour %>% select(x,y,hex))
p <-im_simp %>%
add_count(grp) %>%
filter(n>2) %>%
ggplot() +
theme_void() +
scale_y_reverse() +
geom_bspline_closed(aes(x=x,y=y,fill=hex,group=grp), alpha=0.8, size=0.1)+
scale_fill_identity() +
scale_color_identity()
print(p)
}
create_pebble_art(img_url="https://live.staticflickr.com/65535/49664808511_eec5b4e36b_z.jpg",100)
create_pebble_art(img_url="https://live.staticflickr.com/65535/49664808511_eec5b4e36b_z.jpg",200)
@chichacha
Copy link
Author

ConvexHull_Chisato

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment