'How can I access camera and take photos within my R Shiny App? [closed]

I am willing to make my Shiny App accessing the camera and take photos every 5 seconds in the background. I do not want to see the photos on the screen. I just want them to be stored. I looked into web and found some packages that people are talking about like Rvision, opencv, etc. but I did not find them helpful for my job! Please let me know if there is a way at all to do this in R.

Thanks.



Solution 1:[1]

library(shiny)

ui <- basicPage(
  tags$head(
    tags$script(src = "https://unpkg.com/webcam-easy/dist/webcam-easy.min.js"),
    tags$script(src = "shinyWebcam.js")
  ),
  br(),
  sidebarLayout(
    sidebarPanel(
      width = 3, 
      actionButton("run", "Take photos", class = "btn-block btn-primary"),
      br(),
      actionButton("stop", "Stop webcam", class = "btn-block btn-warning")
    ),
    mainPanel(
      width = 9,
      tags$video(
        id = "webcam", autoplay = "", playsinline = "", width="640", height="480"
      ),
      tags$canvas(id = "canvas", class = "d-none")
    )
  )
)

server <- function(input, output) {}

shinyApp(ui, server)

File shinyWebcam.js, to put in the www subfolder of the shiny app:

$(document).ready(function () {
  const webcamElement = document.getElementById("webcam");
  const canvasElement = document.getElementById("canvas");
  const webcam = new Webcam(webcamElement, "user", canvasElement);
  webcam
    .start()
    .then((result) => {
      console.log("webcam started");
    })
    .catch((err) => {
      console.log(err);
    });
  let interval;
  let i = 0;
  $("#run").on("click", function () {
    interval = setInterval(function () {
      const picture = webcam.snap();
      i++;
      const j = i.toString().padStart(5, "0");
      const filename = "pic" + j;
      const a = document.createElement("a");
      document.body.append(a);
      a.download = filename;
      a.href = picture;
      a.click();
      a.remove();
    }, 5000);
  });
  $("#stop").on("click", function () {
    clearInterval(interval);
    webcam.stop();
  });
});

Perhaps your browser asks you to choose a folder for a download; if so, you have to disable this option in your browser settings.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stéphane Laurent