p5.js 从网络摄像头获取图像

p5.js Getting image from webcam

我制作了一个图像处理程序,用于处理磁盘中的图像。 现在我不想使用磁盘中的图像,而是使用网络摄像头中的图像。

目前我的代码是:

var img;
let capture;

function preload() {
  img = loadImage('file.jpg');
}

function setup(){
  capture = createCapture(VIDEO);
  // new code, something like img = image(capture); ?
}

// my image processing code using img
...

现在,我如何用我的网络摄像头视频捕获的图像文件而不是 file.jpg 填充 img

您可以使用 copy() 函数执行此操作:

let img;
let capture;

function setup() {
  createCanvas(400, 400);
  capture = createCapture(VIDEO);
  capture.hide();
  // wait until the video starts playing to create the image
  capture.elt.addEventListener('playing', mousePressed);
  
  noLoop();
}

function draw() {
  if (img) {
    image(img, 0, 0);
  }
}

function mousePressed() {
  // The capture element is initially smaller than it should be
  if (!img || img.width !== capture.width) {
    img = createImage(capture.width, capture.height);
  }
  img.copy(capture, 0, 0, capture.width, capture.height, 0, 0, img.width, img.height);
  redraw();
}