0

Let's say I have an image like this smiley face below:

Just as an example, a white background with a blue smile drawn on it

I would like to write an R script that returns the pixel coordinates of the pixels that are blue. Ideally I'd want to specify the RGB/HEX/etc value of the blue when using this package/function, rather than using a threshold or a logic calculation where I'm looking at whether or not a pixel is 'white or not white'. I know there are tools and packages in Python and MATLAB but I was wondering if there was a suitable package in R I could use instead. Thanks!

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Package recommendations are generally off topic on this site. That said, once you’ve loaded the image [you’ll have to iterate over the pixel data and compare them with a given colour](https://stackoverflow.com/a/19936295/1968), same as in Python. – Konrad Rudolph Feb 10 '20 at 11:59
  • Thanks Konrad, will remember next time. In the future, if I have questions like "what package do I use", where should I instead be asking this? – EugeneAliev93 Feb 10 '20 at 12:36

1 Answers1

1

You can load the PNG as a 3d array (n_rows x n_columns x (R, G, B, alpha)) using the png package. Then you can do something like this:

find_pixels <- function(png_path, string)
{
  img <- 255 * png::readPNG(png_path)
  R <- as.numeric(paste0("0x", substr(string, 2, 3)))
  G <- as.numeric(paste0("0x", substr(string, 4, 5)))
  B <- as.numeric(paste0("0x", substr(string, 6, 7)))
  which(img[,,1] == R & img[,,2] == B & img[,,3] == G, arr.ind = TRUE)
}

find_pixels("~/smiley.png", "#FAFAFA")
#>      row col
#> [1,]   1   1
#> [2,]   2   1
#> [3,]   3   1
#> [4,]   4   1
#> [5,]   5   1
#> [6,]   6   1
#> ... etc
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87