Reputation: 4346
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.
Upvotes: 0
Views: 694
Reputation: 53089
In ImageMagick command line, Mark's second line works without having to know the other color. So it works for both images without his first line of code.
convert VQZ9Y.png -fill black +opaque white -format "%[fx:100*mean]\%\n" info:
4.54545%
convert Qpdg8.png -fill black +opaque white -format "%[fx:100*mean]\%\n" info:
27.7778%
Upvotes: 1
Reputation: 207375
Sorry, I can't help you with the R
side of things, but a suitable command for the command line that you may be able to adapt is as follows:
convert image.png -fill black +opaque white -format "%[fx:mean*100]" info:
That replaces with black (-fill black
) everything that is not white (+opaque white
) and then calculates the percentage white of the result.
Examples
convert -size 100x10 xc:white -bordercolor red -border 50 a.png # Generate test image
convert a.png -fill black +opaque white -format "%[fx:mean*100]" info: # Determine whites
4.5454
convert -size 100x10 xc:white -bordercolor blue -border 10 a.png # Generate test image
convert a.png -fill black +opaque white -format "%[fx:mean*100]" info: # Determine whites
27.7778
Upvotes: 2
Reputation: 54237
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
Upvotes: 3