1. Dotnet9首页
  2. 大前端
  3. 前端语言
  4. JavaScript

登顶 GitHub 趋势榜,标星1.8k:200 行 JS 代码让画面人物瞬间消失!

登顶 GitHub 趋势榜,标星1.8k:200 行 JS 代码让画面人物瞬间消失!

整理 | 夕颜
出品 | CSDN(ID:CSDNnews)

登顶 GitHub 趋势榜,标星1.8k:200 行 JS 代码让画面人物瞬间消失!

今天,一个名为 Real-Time-Person-Removal(实时人物去除)项目在GitHub上火了,登上近日GitHub Trending第一,目前已经获得1.8k star。 

这个项目的神奇之处在于,只需要在网络浏览器中使用JavaScript,用200多行TensorFlow.js代码,就可以实时让视频画面中的人物对象从复杂的背景中凭空消失! 

这虽然不能让你在现实生活中像哈利·波特一样隐身的梦想成真,但至少在视频、动画里可以体验一把隐身的快感👻👻👻! 

首先奉上GitHub地址:https://github.com/jasonmayes/Real-Time-Person-Removal

1 这个项目能干啥?

本项目的作者@jasonmayes(Jason Mayes)是谷歌的一名资深开发者,是机器智能研究和高级开发的倡导者,作为一名TensorFlow.js专家,他拥有超过15年使用新技术开发创新Web解决方案的经验。 

他在项目介绍中表示,这段代码的目的在于随着时间的推移学习视频背景的构成,让作者可以尝试从背景中移除任何人物,而所有效果都是使用TensorFlow.js在浏览器中实时实现的。 

但同时作者表示,这只是一个实验,并非在所有情况下都是完美的。

登顶 GitHub 趋势榜,标星1.8k:200 行 JS 代码让画面人物瞬间消失!
消失的人

2 废话不多说,上代码!

可能有人会觉得在复杂的背景下实现“隐身”是很复杂的吧,而且还是实时的,但实际上实现这样的效果却只需要200多行JS代码:

/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */

/********************************************************************
 * Real-Time-Person-Removal Created by Jason Mayes 2020.
 *
 * Get latest code on my Github:
 * https://github.com/jasonmayes/Real-Time-Person-Removal
 *
 * Got questions? Reach out to me on social:
 * Twitter: @jason_mayes
 * LinkedIn: https://www.linkedin.com/in/creativetech
 ********************************************************************/

const video = document.getElementById('webcam');
const liveView = document.getElementById('liveView');
const demosSection = document.getElementById('demos');
const DEBUG = false;

// An object to configure parameters to set for the bodypix model.
// See github docs for explanations.
const bodyPixProperties = {
  architecture: 'MobileNetV1',
  outputStride: 16,
  multiplier: 0.75,
  quantBytes: 4
};

// An object to configure parameters for detection. I have raised
// the segmentation threshold to 90% confidence to reduce the
// number of false positives.
const segmentationProperties = {
  flipHorizontal: false,
  internalResolution: 'high',
  segmentationThreshold: 0.9
};

// Must be even. The size of square we wish to search for body parts.
// This is the smallest area that will render/not render depending on
// if a body part is found in that square.
const SEARCH_RADIUS = 300;
const SEARCH_OFFSET = SEARCH_RADIUS / 2;


// RESOLUTION_MIN should be smaller than SEARCH RADIUS. About 10x smaller seems to 
// work well. Effects overlap in search space to clean up body overspill for things
// that were not classified as body but infact were.
const RESOLUTION_MIN = 20;


// Render returned segmentation data to a given canvas context.
function processSegmentation(canvas, segmentation) {
  var ctx = canvas.getContext('2d');

  // Get data from our overlay canvas which is attempting to estimate background.
  var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  var data = imageData.data;

  // Get data from the live webcam view which has all data.
  var liveData = videoRenderCanvasCtx.getImageData(0, 0, canvas.width, canvas.height);
  var dataL = liveData.data;

  // Now loop through and see if pixels contain human parts. If not, update 
  // backgound understanding with new data.
  for (let x = RESOLUTION_MIN; x < canvas.width; x += RESOLUTION_MIN) {
    for (let y = RESOLUTION_MIN; y < canvas.height; y += RESOLUTION_MIN) {
      // Convert xy co-ords to array offset.
      let n = y * canvas.width + x;

      let foundBodyPartNearby = false;

      // Let's check around a given pixel if any other pixels were body like.
      let yMin = y - SEARCH_OFFSET;
      yMin = yMin < 0 ? 0: yMin;

      let yMax = y + SEARCH_OFFSET;
      yMax = yMax > canvas.height ? canvas.height : yMax;

      let xMin = x - SEARCH_OFFSET;
      xMin = xMin < 0 ? 0: xMin;

      let xMax = x + SEARCH_OFFSET;
      xMax = xMax > canvas.width ? canvas.width : xMax;

      for (let i = xMin; i < xMax; i++) {
        for (let j = yMin; j < yMax; j++) {

          let offset = j * canvas.width + i;
          // If any of the pixels in the square we are analysing has a body
          // part, mark as contaminated.
          if (segmentation.data[offset] !== 0) {
            foundBodyPartNearby = true;
            break;
          } 
        }
      }

      // Update patch if patch was clean.     
      if (!foundBodyPartNearby) {
        for (let i = xMin; i < xMax; i++) {
          for (let j = yMin; j < yMax; j++) {
            // Convert xy co-ords to array offset.
            let offset = j * canvas.width + i;


            data[offset * 4] = dataL[offset * 4];    
            data[offset * 4 + 1] = dataL[offset * 4 + 1];
            data[offset * 4 + 2] = dataL[offset * 4 + 2];
            data[offset * 4 + 3] = 255;            
          }
        }
      } else {
        if (DEBUG) {
          for (let i = xMin; i < xMax; i++) {
            for (let j = yMin; j < yMax; j++) {
              // Convert xy co-ords to array offset.
              let offset = j * canvas.width + i;


              data[offset * 4] = 255;    
              data[offset * 4 + 1] = 0;
              data[offset * 4 + 2] = 0;
              data[offset * 4 + 3] = 255;            
            }
          } 
        }
      }


    }
  }
  ctx.putImageData(imageData, 0, 0);
}

// Let's load the model with our parameters defined above.
// Before we can use bodypix class we must wait for it to finish
// loading. Machine Learning models can be large and take a moment to
// get everything needed to run.
var modelHasLoaded = false;
var model = undefined;

model = bodyPix.load(bodyPixProperties).then(function (loadedModel) {
  model = loadedModel;
  modelHasLoaded = true;
  // Show demo section now model is ready to use.
  demosSection.classList.remove('invisible');
});

/********************************************************************
// Continuously grab image from webcam stream and classify it.
********************************************************************/

var previousSegmentationComplete = true;

// Check if webcam access is supported.
function hasGetUserMedia() {
  return !!(navigator.mediaDevices &&
    navigator.mediaDevices.getUserMedia);
}

// This function will repeatidly call itself when the browser is ready to process
// the next frame from webcam.
function predictWebcam() {
  if (previousSegmentationComplete) {
    // Copy the video frame from webcam to a tempory canvas in memory only (not in the DOM).
    videoRenderCanvasCtx.drawImage(video, 0, 0);
    previousSegmentationComplete = false;
    // Now classify the canvas image we have available.
    model.segmentPerson(videoRenderCanvas, segmentationProperties).then(function(segmentation) {
      processSegmentation(webcamCanvas, segmentation);
      previousSegmentationComplete = true;
    });
  }

  // Call this function again to keep predicting when the browser is ready.
  window.requestAnimationFrame(predictWebcam);
}

// Enable the live webcam view and start classification.
function enableCam(event) {
  if (!modelHasLoaded) {
    return;
  }

  // Hide the button.
  event.target.classList.add('removed');  

  // getUsermedia parameters.
  const constraints = {
    video: true
  };

  // Activate the webcam stream.
  navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
    video.addEventListener('loadedmetadata', function() {
      // Update widths and heights once video is successfully played otherwise
      // it will have width and height of zero initially causing classification
      // to fail.
      webcamCanvas.width = video.videoWidth;
      webcamCanvas.height = video.videoHeight;
      videoRenderCanvas.width = video.videoWidth;
      videoRenderCanvas.height = video.videoHeight;
      let webcamCanvasCtx = webcamCanvas.getContext('2d');
      webcamCanvasCtx.drawImage(video, 0, 0);
    });

    video.srcObject = stream;

    video.addEventListener('loadeddata', predictWebcam);
  });
}

// We will create a tempory canvas to render to store frames from 
// the web cam stream for classification.
var videoRenderCanvas = document.createElement('canvas');
var videoRenderCanvasCtx = videoRenderCanvas.getContext('2d');

// Lets create a canvas to render our findings to the DOM.
var webcamCanvas = document.createElement('canvas');
webcamCanvas.setAttribute('class', 'overlay');
liveView.appendChild(webcamCanvas);

// If webcam supported, add event listener to button for when user
// wants to activate it.
if (hasGetUserMedia()) {
  const enableWebcamButton = document.getElementById('webcamButton');
  enableWebcamButton.addEventListener('click', enableCam);
} else {
  console.warn('getUserMedia() is not supported by your browser');
}

CSS(代码不全,可查看上文链接源码):

 /**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */




 /******************************************************
 * Stylesheet by Jason Mayes 2020.
 *
 * Get latest code on my Github:
 * https://github.com/jasonmayes/Real-Time-Person-Removal
 * Got questions? Reach out to me on social:
 * Twitter: @jason_mayes
 * LinkedIn: https://www.linkedin.com/in/creativetech
 *****************************************************/




body {
 font-family: helvetica, arial, sans-serif;
 margin: 2em;
 color: #3D3D3D;

}





h1 {
    44 font-style: italic;
    45 color: #FF6F00;
    46
}





h2 {
 clear: both;

}





em {
 font-weight: bold;

}





video {
 clear: both;
 display: block;

}





section {
 opacity: 1;
 transition: opacity 500ms ease-in-out;

}





header, footer {
 clear: both;

}





button {
 z-index: 1000;
 position: relative;

}





.removed {
 display: none;

}





.invisible {
 opacity: 0.2;

}





.note {
 font-style: italic;
 font-size: 130%;

}





.webcam {
 position: relative;

}





.webcam, .classifyOnClick {
 position: relative;
 float: left;
 width: 48%;
 margin: 2% 1%;
 cursor: pointer;

}





.webcam p, .classifyOnClick p {
 position: absolute;
 padding: 5px;
 background-color: rgba(255, 111, 0, 0.85);
 color: #FFF;
 border: 1px dashed rgba(255, 255, 255, 0.7);
 z-index: 2;
 font-size: 12px;

}





.highlighter {
 background: rgba(0, 255, 0, 0.25);
 border: 1px dashed #fff;
 z-index: 1;
 position: absolute;

}





.classifyOnClick {
 z-index: 0;
 position: relative;

}





.classifyOnClick canvas, .webcam canvas.overlay {
 opacity: 1;
 170 top: 0;
 left: 0;
 z-index: 2;

}





#liveView {
 transform-origi

Html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Disappearing People Project</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="author" content="Jason Mayes">




    <!-- Import the webpage's stylesheet -->
    <link rel="stylesheet" href="/style.css">




    <!-- Import TensorFlow.js library -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js" type="text/javascript"></script>
  </head>
  <body>
    <h1>Disappearing People Project</h1>

    <header class="note">
      <h2>Removing people from complex backgrounds in real time using TensorFlow.js</h2>
    </header>




    <h2>How to use</h2>
    <p>Please wait for the model to load before trying the demos below at which point they will become visible when ready to use.</p>
    <p>Here is a video of what you can expect to achieve using my custom algorithm. The top is the actual footage, the bottom video is with the real time removal of people working in JavaScript!</p>
    <iframe width="540" height="812" src="https://www.youtube.com/embed/0LqEuc32uTc?controls=0&autoplay=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

    <section id="demos" class="invisible">




      <h2>Demo: Webcam live removal</h2>
      <p>Try this out using your webcam. Stand a few feet away from your webcam and start walking around... Watch as you slowly disappear in the bottom preview.</p>

      <div id="liveView" class="webcam">
        <button id="webcamButton">Enable Webcam</button>
        <video id="webcam" autoplay></video>
      </div>
    </section>





    <!-- Include the Glitch button to show what the webpage is about and
         to make it easier for folks to view source and remix -->
    <div class="glitchButton" style="position:fixed;top:20px;right:20px;"></div>
    <script src="https://button.glitch.me/button.js"></script>

    <!-- Load the bodypix model to recognize body parts in images -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/body-pix@2.0"></script>

    <!-- Import the page's JavaScript to do some stuff -->
    <script src="/script.js" defer></script>
  </body>

3 实时演示

你也可以在自己的Web浏览器中根据自己的喜好试着复现一下: 

Codepen.io:https://codepen.io/jasonmayes/pen/GRJqgmaGlitch.com:https://glitch.com/~disappearing-people 

等待模型加载完成,然后就可以使用了。 

这是使用作者自定义算法实现的视频。上半部分是实际镜头,底部是用JavaScript实时删除人物的视频。 

用你自己的网络摄像头试一下,要距离摄像头几英尺远,然后来回走动,在底部预览中你会慢慢从画面中消失。赶快试试吧,使用效果别忘了留言和大家一起分享哦!

【End】

原文出处:微信公众号【CSDN】,作者【CSDN App】

原文链接:https://mp.weixin.qq.com/s/zOclR8sOgTHkuGz8Bmsliw

本文观点不代表Dotnet9立场,转载请联系原作者。

发表评论

登录后才能评论

评论列表(1条)

  • 站长-沙漠尽头的狼
    Dotnet9 2020年2月21日 15:38

    原文部分代码不全,可从文中给出的链接中下载源码测试。