如何制作一个闪亮的应用程序,允许在光栅图像上绘制多个多边形?

How to make a shiny app that allows to draw multiple polygons on raster images?

我想开发一个 shiny 应用程序,用户可以在其中在 raster 图像上绘制多边形。一旦用户完成绘制多边形,我希望应用程序向他们显示 table 个选定像素。

例如,terra提供了一个函数draw,可以用作draw("polygon")。但是,我无法让它与我的 shiny 应用程序一起使用。

app的基本思路如下(有问题的部分我已经用#注释掉了):

library(terra)
library(shiny)

r = rast(system.file("ex/elev.tif", package="terra"))

ui = fluidPage(
        plotOutput("map"),
        tableOutput("chosen_pixels")
)

server = function(input, output, session) {
        output$map = renderPlot({
                plot(r)
                # draw("polygon") # I comment it otherwise the app does not run
        })
        
        # output$chosen_pixels = renderPlot({
                # here I want to write code that shows a table of chosen pixels
        #})
}

shinyApp(ui, server)
library(shiny)
library(tidyverse)

ui <- basicPage(
  plotOutput("plot1", click = "plot_click"),
  tableOutput("table"),
  textInput("polygon_name", label = "Polygon name", value = "polygon 1")
)

server <- function(input, output) {
  coords <- reactiveVal(value = tibble(x = numeric(), y = numeric(), name = character()))

  observeEvent(input$plot_click, {
    add_row(coords(),
      x = isolate(input$plot_click$x),
      y = isolate(input$plot_click$y),
      name = isolate(input$polygon_name)
    ) %>% coords()
  })

  output$plot1 <- renderPlot({
    plot(r)
    
    coords() %>%
      nest(-name) %>%
      deframe() %>%
      map(~ polygon(.x$x, .x$y))
  })

  output$table <- renderTable(coords())
}

shinyApp(ui, server)