JavaScript:可靠地提取视频帧

时间:2015-09-21 16:02:04

标签: javascript html5 video canvas

我正在开发一个客户端项目,该项目允许用户提供视频文件并对其应用基本操作。我正在尝试可靠地从视频中提取帧。目前我有<video>我正在加载所选视频,然后按如下方式拉出每一帧:

  1. 寻找开头
  2. 暂停视频
  3. <video>绘制到<canvas>
  4. 使用.toDataUrl()
  5. 从画布中捕获帧
  6. 向前搜索1/30秒(1帧)。
  7. 冲洗并重复
  8. 这是一个相当低效的过程,更具体地说,证明是不可靠的,因为我经常遇到卡住的帧。这似乎是因为它在绘制到画布之前没有更新实际的<video>元素。

    我宁愿不必将原始视频上传到服务器只是为了分割帧,然后将它们下载回客户端。

    非常感谢任何有关更好方法的建议。唯一需要注意的是,我需要它使用浏览器支持的任何格式(在JS中解码不是一个很好的选择)。

2 个答案:

答案 0 :(得分:16)

Mostly taken from this great answer的{p> GameAlchemist

由于浏览器不尊重视频&#39;帧速率,但相反&#34;使用一些技巧在电影的帧速率和屏幕的刷新率之间进行匹配&#34;,你的假设每隔30秒,一个新的帧将是画是非常不准确的 但是,当currentTime发生变化时,timeupdate event会触发,我们可以假设画了一个新帧。

所以,我会这样做:

&#13;
&#13;
document.querySelector('input').addEventListener('change', extractFrames, false);

function extractFrames() {
  var video = document.createElement('video');
  var array = [];
  var canvas = document.createElement('canvas');
  var ctx = canvas.getContext('2d');
  var pro = document.querySelector('#progress');

  function initCanvas(e) {
    canvas.width = this.videoWidth;
    canvas.height = this.videoHeight;
  }

  function drawFrame(e) {
    this.pause();
    ctx.drawImage(this, 0, 0);
    /* 
    this will save as a Blob, less memory consumptive than toDataURL
    a polyfill can be found at
    https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob#Polyfill
    */
    canvas.toBlob(saveFrame, 'image/jpeg');
    pro.innerHTML = ((this.currentTime / this.duration) * 100).toFixed(2) + ' %';
    if (this.currentTime < this.duration) {
      this.play();
    }
  }

  function saveFrame(blob) {
    array.push(blob);
  }

  function revokeURL(e) {
    URL.revokeObjectURL(this.src);
  }
  
  function onend(e) {
    var img;
    // do whatever with the frames
    for (var i = 0; i < array.length; i++) {
      img = new Image();
      img.onload = revokeURL;
      img.src = URL.createObjectURL(array[i]);
      document.body.appendChild(img);
    }
    // we don't need the video's objectURL anymore
    URL.revokeObjectURL(this.src);
  }
  
  video.muted = true;

  video.addEventListener('loadedmetadata', initCanvas, false);
  video.addEventListener('timeupdate', drawFrame, false);
  video.addEventListener('ended', onend, false);

  video.src = URL.createObjectURL(this.files[0]);
  video.play();
}
&#13;
<input type="file" accept="video/*" />
<p id="progress"></p>
&#13;
&#13;
&#13;

答案 1 :(得分:5)

这是一个从this question进行了调整的工作功能:

async function extractFramesFromVideo(videoUrl, fps=25) {
  return new Promise(async (resolve) => {

    // fully download it first (no buffering):
    let videoBlob = await fetch(videoUrl).then(r => r.blob());
    let videoObjectUrl = URL.createObjectURL(videoBlob);
    let video = document.createElement("video");

    let seekResolve;
    video.addEventListener('seeked', async function() {
      if(seekResolve) seekResolve();
    });

    video.src = videoObjectUrl;

    // workaround chromium metadata bug (https://stackoverflow.com/q/38062864/993683)
    while((video.duration === Infinity || isNaN(video.duration)) && video.readyState < 2) {
      await new Promise(r => setTimeout(r, 1000));
      video.currentTime = 10000000*Math.random();
    }
    let duration = video.duration;

    let canvas = document.createElement('canvas');
    let context = canvas.getContext('2d');
    let [w, h] = [video.videoWidth, video.videoHeight]
    canvas.width =  w;
    canvas.height = h;

    let frames = [];
    let interval = 1 / fps;
    let currentTime = 0;

    while(currentTime < duration) {
      video.currentTime = currentTime;
      await new Promise(r => seekResolve=r);

      context.drawImage(video, 0, 0, w, h);
      let base64ImageData = canvas.toDataURL();
      frames.push(base64ImageData);

      currentTime += interval;
    }
    resolve(frames);
  });
});

}

用法:

let frames = await extractFramesFromVideo("https://example.com/video.webm");

请注意,除非您可能使用ffmpeg.js,否则目前尚没有简便的方法来确定视频的实际/自然帧速率,但这是一个10兆以上的javascript文件(因为它是实际ffmpeg库的脚本端口) ,这显然是巨大的)。