2017-10-19 144 views
0

我想呈现给定的字符串作为灰度图像,随后对其执行一些简单的操作。我知道text()函数。不幸的是,这需要打开图形设备。为了我的目的,将灰度图像直接存储在矩阵中会更加方便和高效。获取呈现的文本的灰度图像作为矩阵

获得给定字符串渲染灰度图像矩阵表示的有效方法是什么?

+0

你也许可以做到这一点与'magik'包 - 但它会使用图形设备 –

回答

0

magick包为理查德·德福建议是关键,解决这个问题:

# 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]]))