如何准确过滤RGB值以实现色度键效果

Aka*_*mar 9 javascript chromakey

我刚刚阅读了教程并尝试了这个例子.所以我从网上下载了一个视频供我自己测试.我所要做的就是调整条件下的rgb值

这里是示例中的示例代码

computeFrame: function() {
    this.ctx1.drawImage(this.video, 0, 0, this.width, this.height);
    let frame = this.ctx1.getImageData(0, 0, this.width, this.height);
    let l = frame.data.length / 4;

    for (let i = 0; i < l; i++) {
      let r = frame.data[i * 4 + 0];
      let g = frame.data[i * 4 + 1];
      let b = frame.data[i * 4 + 2];
      if (g > 100 && r > 100 && b < 43)
        frame.data[i * 4 + 3] = 0;
    }
    this.ctx2.putImageData(frame, 0, 0);
    return;
  }
Run Code Online (Sandbox Code Playgroud)

在教程示例中,它过滤掉黄色(我猜不是黄色)颜色.我下载的示例视频使用绿色背景.所以我在if条件下调整了rgb值以获得所需的结果

多次尝试后,我设法得到了这个.

在此输入图像描述

现在我想知道的是如何在不猜测的情况下完美地过滤掉绿屏(或任何其他屏幕).或随机调整值.

只是猜测它需要几个小时才能完全正确.这只是一个真实世界应用程序的示例.它可能需要更多.

注意:该示例现在在Firefox中工作..

Ent*_*ity 8

你可能只需要一个更好的算法.这是一个,它并不完美,但你可以轻松调整它.

就这样做吧

基本上你只需要一个颜色选择器,并从视频中选择最亮和最暗的值(分别将RGB值放在l_和d_变量中).如果需要,您可以稍微调整公差,但通过使用颜色选择器选择不同的区域来正确获取l_和r_值将为您提供更好的密钥.

let l_r = 131,
    l_g = 190,
    l_b = 137,

    d_r = 74,
    d_g = 148,
    d_b = 100;

let tolerance = 0.05;

let processor = {
  timerCallback: function() {
    if (this.video.paused || this.video.ended) {
      return;
    }
    this.computeFrame();
    let self = this;
    setTimeout(function () {
        self.timerCallback();
      }, 0);
  },

  doLoad: function() {
    this.video = document.getElementById("video");
    this.c1 = document.getElementById("c1");
    this.ctx1 = this.c1.getContext("2d");
    this.c2 = document.getElementById("c2");
    this.ctx2 = this.c2.getContext("2d");
    let self = this;
    this.video.addEventListener("play", function() {
        self.width = self.video.videoWidth;
        self.height = self.video.videoHeight;
        self.timerCallback();
      }, false);
  },

  calculateDistance: function(c, min, max) {
      if(c < min) return min - c;
      if(c > max) return c - max;

      return 0;
  },

  computeFrame: function() {
    this.ctx1.drawImage(this.video, 0, 0, this.width, this.height);
    let frame = this.ctx1.getImageData(0, 0, this.width, this.height);
        let l = frame.data.length / 4;

    for (let i = 0; i < l; i++) {
      let _r = frame.data[i * 4 + 0];
      let _g = frame.data[i * 4 + 1];
      let _b = frame.data[i * 4 + 2];

      let difference = this.calculateDistance(_r, d_r, l_r) + 
                       this.calculateDistance(_g, d_g, l_g) +
                       this.calculateDistance(_b, d_b, l_b);
      difference /= (255 * 3); // convert to percent
      if (difference < tolerance)
        frame.data[i * 4 + 3] = 0;
    }
    this.ctx2.putImageData(frame, 0, 0);
    return;
  }
};
// :/ 
Run Code Online (Sandbox Code Playgroud)