问题描述
我有一个 excel 句子列表,我正在尝试将每个句子注释到同一个模板图像上并单独保存每个图像文件(即我将有 20 个图像,背景相同但文本不同 - 类似于 Word 的邮件合并功能与文档).
I have a excel list of sentences and I am trying to annotate each one onto the same template image and save each image file individually (i.e. I will have 20 images, with the same background but different text - akin to Word's Mail Merge feature with documents).
为此,我使用了 R 包 magick
的 image_annotate
和 image_write
命令.我的假设是将其放入 for
循环中即可完成此任务.
To do this, I am using the R package magick
's image_annotate
and image_write
commands. My assumption was that putting it into a for
loop would accomplish this task.
我使用了以下代码:
QuoteList=read.csv("wordlist.csv", stringsAsFactors = F, header = T)
myTemplate=image_read("template.png")
for (i in 1:nrow(QuoteList))
{
thisImage[i]=image_annotate(myTemplate, QuoteList$myquote[i])
image_write(thisImage[i], format = "png")
}
但是我得到了错误:
Error in magick_image_replace(x, i, value) : subscript out of bounds
我不完全确定我做错了什么,非常感谢对此或任何可能的替代解决方案的任何帮助.提前致谢.
I am not entirely sure what I am doing wrong and would highly appreciate any help on this or any possible alternative solutions. Thanks in advance.
推荐答案
您需要在每次迭代时替换您正在编写的对象,但每次都写入一个新的文件名:
You need to replace the object you're writing with each iteration, but write to a new filename each time:
for (i in 1:nrow(QuoteList)){
thisImage = image_annotate(myTemplate, QuoteList$myquote[i])
image_write(thisImage, format <- "png", path = paste0(i, ".png"))
}
这篇关于在 R 上使用 Magick 编写多个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!