Skip to content

Instantly share code, notes, and snippets.

@dakvid
Created May 26, 2020 21:16
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 dakvid/6e0cc85b79dbbc2e70b5e32b458ebe4f to your computer and use it in GitHub Desktop.
Save dakvid/6e0cc85b79dbbc2e70b5e32b458ebe4f to your computer and use it in GitHub Desktop.
Get pixel colours from an image using R and ImageMagick
# 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")
@veebch
Copy link

veebch commented Feb 26, 2023

Should that be
read_table ('test.txt, col_names = F, skip = 1) %>%
?

@dakvid
Copy link
Author

dakvid commented Feb 27, 2023

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