Reputation: 3
Let's say I have an image like this smiley face below:
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!
Upvotes: 0
Views: 197
Reputation: 174478
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
Upvotes: 1