rmagick

Output percentage white content of image using imagemagick R


I am rendering two versions of the same web page and would like to know the most efficient use of space. I aim to do this by outputting the pages as images and looking at the percentage of the page that is white. The less white, the more efficient (my criteria!)

How can imagemagick in R be used to output the % white content of an image? I see it is possible through command line, but can't find anything on doing this inside R.


Solution

  • If you want exactly white (not lightgray or something, too), you can do it like this:

    download.file("https://www.gravatar.com/avatar/b1cdf616876083f7c5ec1a49fc357530?s=328&d=identicon&r=PG", tf <- tempfile(fileext = ".png"), mode="wb")
    f <- function(fn) {
      require(magick)
      img <- image_read(tf)
      r <- as.raster(img)
      sum(substr(tolower(r), 1, 7) == "#ffffff") / length(r) * 100
    }
    f(tf)
    # [1] 44.33931