百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

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

bigegpt 2024-08-27 11:57 2 浏览

整理 | 夕颜

出品 | CSDN(ID:CSDNnews)

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

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

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

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


这个项目能干啥?

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

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

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

消失的人


废话不多说,上代码!

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

  1/**
  2 * @license
  3 * Copyright 2018 Google LLC. All Rights Reserved.
  4 * Licensed under the Apache License, Version 2.0 (the "License");
  5 * you may not use this file except in compliance with the License.
  6 * You may obtain a copy of the License at
  7 *
  8 * http://www.apache.org/licenses/LICENSE-2.0
  9 *
 10 * Unless required by applicable law or agreed to in writing, software
 11 * distributed under the License is distributed on an "AS IS" BASIS,
 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13 * See the License for the specific language governing permissions and
 14 * limitations under the License.
 15 * =============================================================================
 16 */
 17
 18/********************************************************************
 19 * Real-Time-Person-Removal Created by Jason Mayes 2020.
 20 *
 21 * Get latest code on my Github:
 22 * https://github.com/jasonmayes/Real-Time-Person-Removal
 23 *
 24 * Got questions? Reach out to me on social:
 25 * Twitter: @jason_mayes
 26 * LinkedIn: https://www.linkedin.com/in/creativetech
 27 ********************************************************************/
 28
 29const video = document.getElementById('webcam');
 30const liveView = document.getElementById('liveView');
 31const demosSection = document.getElementById('demos');
 32const DEBUG = false;
 33
 34// An object to configure parameters to set for the bodypix model.
 35// See github docs for explanations.
 36const bodyPixProperties = {
 37  architecture: 'MobileNetV1',
 38  outputStride: 16,
 39  multiplier: 0.75,
 40  quantBytes: 4
 41};
 42
 43// An object to configure parameters for detection. I have raised
 44// the segmentation threshold to 90% confidence to reduce the
 45// number of false positives.
 46const segmentationProperties = {
 47  flipHorizontal: false,
 48  internalResolution: 'high',
 49  segmentationThreshold: 0.9
 50};
 51
 52// Must be even. The size of square we wish to search for body parts.
 53// This is the smallest area that will render/not render depending on
 54// if a body part is found in that square.
 55const SEARCH_RADIUS = 300;
 56const SEARCH_OFFSET = SEARCH_RADIUS / 2;
 57
 58
 59// RESOLUTION_MIN should be smaller than SEARCH RADIUS. About 10x smaller seems to 
 60// work well. Effects overlap in search space to clean up body overspill for things
 61// that were not classified as body but infact were.
 62const RESOLUTION_MIN = 20;
 63
 64
 65// Render returned segmentation data to a given canvas context.
 66function processSegmentation(canvas, segmentation) {
 67  var ctx = canvas.getContext('2d');
 68
 69  // Get data from our overlay canvas which is attempting to estimate background.
 70  var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
 71  var data = imageData.data;
 72
 73  // Get data from the live webcam view which has all data.
 74  var liveData = videoRenderCanvasCtx.getImageData(0, 0, canvas.width, canvas.height);
 75  var dataL = liveData.data;
 76
 77  // Now loop through and see if pixels contain human parts. If not, update 
 78  // backgound understanding with new data.
 79  for (let x = RESOLUTION_MIN; x < canvas.width; x += RESOLUTION_MIN) {
 80    for (let y = RESOLUTION_MIN; y < canvas.height; y += RESOLUTION_MIN) {
 81      // Convert xy co-ords to array offset.
 82      let n = y * canvas.width + x;
 83
 84      let foundBodyPartNearby = false;
 85
 86      // Let's check around a given pixel if any other pixels were body like.
 87      let yMin = y - SEARCH_OFFSET;
 88      yMin = yMin < 0 ? 0: yMin;
 89
 90      let yMax = y + SEARCH_OFFSET;
 91      yMax = yMax > canvas.height ? canvas.height : yMax;
 92
 93      let xMin = x - SEARCH_OFFSET;
 94      xMin = xMin < 0 ? 0: xMin;
 95
 96      let xMax = x + SEARCH_OFFSET;
 97      xMax = xMax > canvas.width ? canvas.width : xMax;
 98
 99      for (let i = xMin; i < xMax; i++) {
100        for (let j = yMin; j < yMax; j++) {
101
102          let offset = j * canvas.width + i;
103          // If any of the pixels in the square we are analysing has a body
104          // part, mark as contaminated.
105          if (segmentation.data[offset] !== 0) {
106            foundBodyPartNearby = true;
107            break;
108          } 
109        }
110      }
111
112      // Update patch if patch was clean.     
113      if (!foundBodyPartNearby) {
114        for (let i = xMin; i < xMax; i++) {
115          for (let j = yMin; j < yMax; j++) {
116            // Convert xy co-ords to array offset.
117            let offset = j * canvas.width + i;
118
119
120            data[offset * 4] = dataL[offset * 4];    
121            data[offset * 4 + 1] = dataL[offset * 4 + 1];
122            data[offset * 4 + 2] = dataL[offset * 4 + 2];
123            data[offset * 4 + 3] = 255;            
124          }
125        }
126      } else {
127        if (DEBUG) {
128          for (let i = xMin; i < xMax; i++) {
129            for (let j = yMin; j < yMax; j++) {
130              // Convert xy co-ords to array offset.
131              let offset = j * canvas.width + i;
132
133
134              data[offset * 4] = 255;    
135              data[offset * 4 + 1] = 0;
136              data[offset * 4 + 2] = 0;
137              data[offset * 4 + 3] = 255;            
138            }
139          } 
140        }
141      }
142
143
144    }
145  }
146  ctx.putImageData(imageData, 0, 0);
147}
148
149// Let's load the model with our parameters defined above.
150// Before we can use bodypix class we must wait for it to finish
151// loading. Machine Learning models can be large and take a moment to
152// get everything needed to run.
153var modelHasLoaded = false;
154var model = undefined;
155
156model = bodyPix.load(bodyPixProperties).then(function (loadedModel) {
157  model = loadedModel;
158  modelHasLoaded = true;
159  // Show demo section now model is ready to use.
160  demosSection.classList.remove('invisible');
161});
162
163/********************************************************************
164// Continuously grab image from webcam stream and classify it.
165********************************************************************/
166
167var previousSegmentationComplete = true;
168
169// Check if webcam access is supported.
170function hasGetUserMedia() {
171  return !!(navigator.mediaDevices &&
172    navigator.mediaDevices.getUserMedia);
173}
174
175// This function will repeatidly call itself when the browser is ready to process
176// the next frame from webcam.
177function predictWebcam() {
178  if (previousSegmentationComplete) {
179    // Copy the video frame from webcam to a tempory canvas in memory only (not in the DOM).
180    videoRenderCanvasCtx.drawImage(video, 0, 0);
181    previousSegmentationComplete = false;
182    // Now classify the canvas image we have available.
183    model.segmentPerson(videoRenderCanvas, segmentationProperties).then(function(segmentation) {
184      processSegmentation(webcamCanvas, segmentation);
185      previousSegmentationComplete = true;
186    });
187  }
188
189  // Call this function again to keep predicting when the browser is ready.
190  window.requestAnimationFrame(predictWebcam);
191}
192
193// Enable the live webcam view and start classification.
194function enableCam(event) {
195  if (!modelHasLoaded) {
196    return;
197  }
198
199  // Hide the button.
200  event.target.classList.add('removed');  
201
202  // getUsermedia parameters.
203  const constraints = {
204    video: true
205  };
206
207  // Activate the webcam stream.
208  navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
209    video.addEventListener('loadedmetadata', function() {
210      // Update widths and heights once video is successfully played otherwise
211      // it will have width and height of zero initially causing classification
212      // to fail.
213      webcamCanvas.width = video.videoWidth;
214      webcamCanvas.height = video.videoHeight;
215      videoRenderCanvas.width = video.videoWidth;
216      videoRenderCanvas.height = video.videoHeight;
217      let webcamCanvasCtx = webcamCanvas.getContext('2d');
218      webcamCanvasCtx.drawImage(video, 0, 0);
219    });
220
221    video.srcObject = stream;
222
223    video.addEventListener('loadeddata', predictWebcam);
224  });
225}
226
227// We will create a tempory canvas to render to store frames from 
228// the web cam stream for classification.
229var videoRenderCanvas = document.createElement('canvas');
230var videoRenderCanvasCtx = videoRenderCanvas.getContext('2d');
231
232// Lets create a canvas to render our findings to the DOM.
233var webcamCanvas = document.createElement('canvas');
234webcamCanvas.setAttribute('class', 'overlay');
235liveView.appendChild(webcamCanvas);
236
237// If webcam supported, add event listener to button for when user
238// wants to activate it.
239if (hasGetUserMedia()) {
240  const enableWebcamButton = document.getElementById('webcamButton');
241  enableWebcamButton.addEventListener('click', enableCam);
242} else {
243  console.warn('getUserMedia() is not supported by your browser');
244}

CSS:

  1/**
  2 * @license
  3 * Copyright 2018 Google LLC. All Rights Reserved.
  4 * Licensed under the Apache License, Version 2.0 (the "License");
  5 * you may not use this file except in compliance with the License.
  6 * You may obtain a copy of the License at
  7 *
  8 * http://www.apache.org/licenses/LICENSE-2.0
  9 *
 10 * Unless required by applicable law or agreed to in writing, software
 11 * distributed under the License is distributed on an "AS IS" BASIS,
 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13 * See the License for the specific language governing permissions and
 14 * limitations under the License.
 15 * =============================================================================
 16 */
 17
 18
 19
 20
 21/******************************************************
 22 * Stylesheet by Jason Mayes 2020.
 23 *
 24 * Get latest code on my Github:
 25 * https://github.com/jasonmayes/Real-Time-Person-Removal
 26 * Got questions? Reach out to me on social:
 27 * Twitter: @jason_mayes
 28 * LinkedIn: https://www.linkedin.com/in/creativetech
 29 *****************************************************/
 30
 31
 32
 33
 34body {
 35  font-family: helvetica, arial, sans-serif;
 36  margin: 2em;
 37  color: #3D3D3D;
 38}
 39
 40
 41
 42
 43h1 {
 44  font-style: italic;
 45  color: #FF6F00;
 46}
 47
 48
 49
 50
 51h2 {
 52  clear: both;
 53}
 54
 55
 56
 57
 58em {
 59  font-weight: bold;
 60}
 61
 62
 63
 64
 65video {
 66  clear: both;
 67  display: block;
 68}
 69
 70
 71
 72
 73section {
 74  opacity: 1;
 75  transition: opacity 500ms ease-in-out;
 76}
 77
 78
 79
 80
 81header, footer {
 82  clear: both;
 83}
 84
 85
 86
 87
 88button {
 89  z-index: 1000;
 90  position: relative;
 91}
 92
 93
 94
 95
 96.removed {
 97  display: none;
 98}
 99
100
101
102
103.invisible {
104  opacity: 0.2;
105}
106
107
108
109
110.note {
111  font-style: italic;
112  font-size: 130%;
113}
114
115
116
117
118.webcam {
119  position: relative;
120}
121
122
123
124
125.webcam, .classifyOnClick {
126  position: relative;
127  float: left;
128  width: 48%;
129  margin: 2% 1%;
130  cursor: pointer;
131}
132
133
134
135
136.webcam p, .classifyOnClick p {
137  position: absolute;
138  padding: 5px;
139  background-color: rgba(255, 111, 0, 0.85);
140  color: #FFF;
141  border: 1px dashed rgba(255, 255, 255, 0.7);
142  z-index: 2;
143  font-size: 12px;
144}
145
146
147
148
149.highlighter {
150  background: rgba(0, 255, 0, 0.25);
151  border: 1px dashed #fff;
152  z-index: 1;
153  position: absolute;
154}
155
156
157
158
159.classifyOnClick {
160  z-index: 0;
161  position: relative;
162}
163
164
165
166
167.classifyOnClick canvas, .webcam canvas.overlay {
168  opacity: 1;
169
170  top: 0;
171  left: 0;
172  z-index: 2;
173}
174
175
176
177
178#liveView {
179  transform-origi


Html:


 1<!DOCTYPE html>
 2<html lang="en">
 3  <head>
 4    <title>Disappearing People Project</title>
 5    <meta charset="utf-8">
 6    <meta http-equiv="X-UA-Compatible" content="IE=edge">
 7    <meta name="viewport" content="width=device-width, initial-scale=1">
 8    <meta name="author" content="Jason Mayes">
 9
10
11
12
13    <!-- Import the webpage's stylesheet -->
14    <link rel="stylesheet" href="/style.css">
15
16
17
18
19    <!-- Import TensorFlow.js library -->
20    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js" type="text/javascript"></script>
21  </head>
22  <body>
23    <h1>Disappearing People Project</h1>
24
25    <header class="note">
26      <h2>Removing people from complex backgrounds in real time using TensorFlow.js</h2>
27    </header>
28
29
30
31
32    <h2>How to use</h2>
33    <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>
34    <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>
35    <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>
36
37    <section id="demos" class="invisible">
38
39
40
41
42      <h2>Demo: Webcam live removal</h2>
43      <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>
44
45      <div id="liveView" class="webcam">
46        <button id="webcamButton">Enable Webcam</button>
47        <video id="webcam" autoplay></video>
48      </div>
49    </section>
50
51
52
53
54
55    <!-- Include the Glitch button to show what the webpage is about and
56         to make it easier for folks to view source and remix -->
57    <div class="glitchButton" style="position:fixed;top:20px;right:20px;"></div>
58    <script src="https://button.glitch.me/button.js"></script>
59
60    <!-- Load the bodypix model to recognize body parts in images -->
61    <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/body-pix@2.0"></script>
62
63    <!-- Import the page's JavaScript to do some stuff -->
64    <script src="/script.js" defer></script>
65  </bod
66

实时演示

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

Codepen.io:https://codepen.io/jasonmayes/pen/GRJqgma

Glitch.com:https://glitch.com/~disappearing-people

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

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

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

相关推荐

【Docker 新手入门指南】第十章:Dockerfile

Dockerfile是Docker镜像构建的核心配置文件,通过预定义的指令集实现镜像的自动化构建。以下从核心概念、指令详解、最佳实践三方面展开说明,帮助你系统掌握Dockerfile的使用逻...

Windows下最简单的ESP8266_ROTS_ESP-IDF环境搭建与腾讯云SDK编译

前言其实也没啥可说的,只是我感觉ESP-IDF对新手来说很不友好,很容易踩坑,尤其是对业余DIY爱好者搭建环境非常困难,即使有官方文档,或者网上的其他文档,但是还是很容易踩坑,多研究,记住两点就行了,...

python虚拟环境迁移(python虚拟环境conda)

主机A的虚拟环境向主机B迁移。前提条件:主机A和主机B已经安装了virtualenv1.主机A操作如下虚拟环境目录:venv进入虚拟环境:sourcevenv/bin/active(1)记录虚拟环...

Python爬虫进阶教程(二):线程、协程

简介线程线程也叫轻量级进程,它是一个基本的CPU执行单元,也是程序执行过程中的最小单元,由线程ID、程序计数器、寄存器集合和堆栈共同组成。线程的引入减小了程序并发执行时的开销,提高了操作系统的并发性能...

基于网络安全的Docker逃逸(docker)

如何判断当前机器是否为Docker容器环境Metasploit中的checkcontainer模块、(判断是否为虚拟机,checkvm模块)搭配学习教程1.检查根目录下是否存在.dockerenv文...

Python编程语言被纳入浙江高考,小学生都开始学了

今年9月份开始的新学期,浙江省三到九年级信息技术课将同步替换新教材。其中,新初二将新增Python编程课程内容。新高一信息技术编程语言由VB替换为Python,大数据、人工智能、程序设计与算法按照教材...

CentOS 7下安装Python 3.10的完整过程

1.安装相应的编译工具yum-ygroupinstall"Developmenttools"yum-yinstallzlib-develbzip2-develope...

如何在Ubuntu 20.04上部署Odoo 14

Odoo是世界上最受欢迎的多合一商务软件。它提供了一系列业务应用程序,包括CRM,网站,电子商务,计费,会计,制造,仓库,项目管理,库存等等,所有这些都无缝集成在一起。Odoo可以通过几种不同的方式进...

Ubuntu 系统安装 PyTorch 全流程指南

当前环境:Ubuntu22.04,显卡为GeForceRTX3080Ti1、下载显卡驱动驱动网站:https://www.nvidia.com/en-us/drivers/根据自己的显卡型号和...

spark+python环境搭建(python 环境搭建)

最近项目需要用到spark大数据相关技术,周末有空spark环境搭起来...目标spark,python运行环境部署在linux服务器个人通过vscode开发通过远程python解释器执行代码准备...

centos7.9安装最新python-3.11.1(centos安装python环境)

centos7.9安装最新python-3.11.1centos7.9默认安装的是python-2.7.5版本,安全扫描时会有很多漏洞,比如:Python命令注入漏洞(CVE-2015-2010...

Linux系统下,五大步骤安装Python

一、下载Python包网上教程大多是通过官方地址进行下载Python的,但由于国内网络环境问题,会导致下载很慢,所以这里建议通过国内镜像进行下载例如:淘宝镜像http://npm.taobao.or...

centos7上安装python3(centos7安装python3.7.2一键脚本)

centos7上默认安装的是python2,要使用python3则需要自行下载源码编译安装。1.安装依赖yum-ygroupinstall"Developmenttools"...

利用本地数据通过微调方式训练 本地DeepSeek-R1 蒸馏模型

网络上相应的教程基本都基于LLaMA-Factory进行,本文章主要顺着相应的教程一步步实现大模型的微调和训练。训练环境:可自行定义,mac、linux或者window之类的均可以,本文以ma...

【法器篇】天啦噜,库崩了没备份(天啦噜是什么意思?)

背景数据库没有做备份,一天突然由于断电或其他原因导致无法启动了,且设置了innodb_force_recovery=6都无法启动,里面的数据怎么才能恢复出来?本例采用解析建表语句+表空间传输的方式进行...