Search code examples
rstringmatrixgrayscale

Obtain rendered grayscale image of text as a matrix


I want to render a given string as a grayscale image and subsequently perform some simple manipulations on it. I am aware of the text() function. Unfortunately this requires opening a graphical device. For my purpose it would be a lot more convenient and efficient to directly store the grayscale image in a matrix instead.

What is an efficient way of obtaining a matrix representation of the rendered grayscale image of a given string?


Solution

  • The magick package as suggested by Richard Telford was key to solving the question:

    # Load the package
    require(magick)
    
    # Create white canvas initializing magick graphical device
    img <- image_graph(width = 140, height = 40, bg = "white", pointsize = 20,
                       res = 120, clip = TRUE, antialias = TRUE)
    # Set margins to 0
    par(mar = c(0,0,0,0))  
    
    # Initialize plot & print text
    plot(c(0,1), axes = FALSE, main = "", xlab = "", ylab = "", col = "white")
    text(0.95, 0.42, "Test", pos = 4, family = "mono", font = 2)
    
    # Close the magick image device
    dev.off() 
    
    # Convert to grayscale & extract pixelmatrix as integers
    img <- image_convert(img, colorspace = "gray")  
    target <- drop(as.integer(img[[1]]))