Search code examples
rpngpixel

Reading png as a N x 3 matrix in R


I would like to read a simple black/white picture in png format into R. I need 3 information for each pixel, the x, y coordinates and color information(0 for white, 1 for black).

I need this information to run a function that checks if there are any closed white elements in the picture or not.

Any tips will be more than welcome. Thanks!

enter image description here


Solution

  • This appears to be almost trivial if you have imager package installed. The color numbers here are inverted, but you should be able to change this without a problem.

    library(imager)
    
    xy <- load.image("vds9S.png")
    head(as.data.frame(xy))
    
      x y value
    1 1 1     1
    2 2 1     1
    3 3 1     1
    4 4 1     1
    5 5 1     1
    6 6 1     1