Created
May 26, 2020 21:16
-
-
Save dakvid/6e0cc85b79dbbc2e70b5e32b458ebe4f to your computer and use it in GitHub Desktop.
Get pixel colours from an image using R and ImageMagick
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Create a pixel chart of a picture, inspired by https://blog.datawrapper.de/weekly-chart-data-art-scatterplot-with-a-pearl-earring/ | |
# My workflow: | |
# Open an image in GIMP, scale to desired size and change Mode to Indexed with max number of colours. | |
# Run following R code to get coordinates and RGB. (Alternatively could use imagemagick in command line and eg sed/awk.) | |
# Load CSV into Datawrapper; manually set colours (if few enough) or use API. | |
library(magrittr) | |
library(magick) | |
library(readr) | |
library(stringr) | |
library(dplyr) | |
test <- image_read("68_index80.png") | |
image_convert(test, "txt") %>% image_write("test.txt") | |
pixels <- | |
read_table("pixels.txt", col_names = F, skip = 1) %>% | |
set_names("source") %>% | |
mutate( | |
x = source %>% str_extract("^[0-9]+"), | |
y = source %>% str_extract(",[0-9]+") %>% str_replace(",", ""), | |
hex = source %>% str_extract("#[0-9A-F]+") | |
) %>% | |
select(-source) | |
write_csv(pixels, "pixels.csv") |
Yes, "test.txt"
- I think I tried to change my code to be a bit more generic but obviously didn't run it for a sanity check. 🤦🏻♂️
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Should that be
read_table ('test.txt, col_names = F, skip = 1) %>%
?