r - 在 R Shiny 中叠加图像
问题描述
编辑:用魔法解决了 - 非常感谢你们 :) GitHub repo中的更新版本,适用于任何对驯鹿的故事感兴趣的人。
我对 R 很陌生,刚认识R Shiny。然而,我正在尝试做一个驯鹿发电机。基本原理:组合不同层次的图像以创建您的个人驯鹿。例如,用按钮切换外套颜色,而轮廓仍然留在顶部。理想情况下,它最终应该看起来像这样(我用 GIMP 绘制的预览):
首先,我设法将图像放入 Shiny 并在两件带有单选按钮的外套之间切换。但是,我不知道如何在同一位置同时显示图像,因此轮廓将是外套顶部的额外层。
你可以在这里看到问题:
这是我的代码。由于文件名部分是由单选按钮输入生成的,所以我留下了这样的路径。
library(shiny)
ui <- fluidPage(
titlePanel("R-eindeer"),
sidebarLayout(
sidebarPanel(
radioButtons("check1","coat colour", choices = c("grey","brown"))
),
mainPanel(
imageOutput("reindeer_coat"),
imageOutput("reindeer_outline")
)
)
)
server <- function(input,output){
getImage <- reactive({
list(src = paste0("./coat/reindeer_", input$check1, ".png"),
width = 500,
height = 500)
})
output$reindeer_coat <- renderImage({
getImage()
}, deleteFile = FALSE)
output$reindeer_outline <- renderImage({
return(list(src = "./outlines/reindeer_outline.png",
width = 500,
height = 500,
contentType = 'image/png'))
}, deleteFile = FALSE)
}
shinyApp(ui = ui, server = server)
我将不胜感激任何帮助。即使解决了这个问题,还有很长的路要走——但也许我可以学得足够快,在圣诞节前完成工作;-)
PS:您可以在我刚刚创建的Git 存储库中找到所有文件夹、图像层和其他信息。此外,即使您无法解决我的问题:请随意使用图像并传递圣诞精神。驯鹿内容应始终免费。链接到 GitHub 存储库
解决方案
如评论中所述,magick
可以为您做到这一点!具体来说,image_mosaic
将叠加图像。
试试这个:
library(shiny)
library(magick)
ui <- fluidPage(
titlePanel("R-eindeer"),
sidebarLayout(
sidebarPanel(
radioButtons("check1","coat colour", choices = c("grey","brown"))
),
mainPanel(
imageOutput("reindeer")
)
)
)
server <- function(input,output){
get_image <- function(type, color) {
image_read(file.path(type, paste0(color, ".png")))
}
output$reindeer <- renderImage({
# load the images
coat <- get_image("coat", paste0("reindeer_", input$check1))
outline <- get_image("outlines", "reindeer_outline")
# make the reindeer: overlay in order
reindeer <- c(coat, outline)
# create a temp file
tmpfile <- reindeer %>%
image_mosaic() %>%
image_flatten() %>%
image_write(tempfile(fileext='jpg'), format = 'jpg')
# render the file
return(list(src = tmpfile,
height = 300,
width = 300,
alt = "Your reindeer",
contentType = "image/jpg"))
}, deleteFile = TRUE)
}
shinyApp(ui = ui, server = server)
推荐阅读
- python - 如果没有指定参数,如何将值添加到将使用的函数?
- python - 如何在 y 轴上获得正确的顺序(matplotlob(P 2.7)正确
- sql - SQL - 包括空字段
- html - justify-self css 属性没有产生预期的效果
- javascript - 如何使用 Javascript 创建多个不和谐机器人状态
- css - 第一个字母超出段落框。如何解决?
- python-3.x - 关于 rnn.pack_padded_sequence 的用法
- sublimetext3 - Sublime Text 3 正在转换带有驼峰名称的下划线函数
- html - 如何将默认值传递给
- java - Instagram 类型模式视图