200行代码实现视频人物实时去除

今天在GitHub上发现了一个好玩的代码,短短几百行代码就实现了从复杂的背景视频中去除人物,不得不说这位大佬比较厉害。

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

耐不住激动就赶快试了一下,虽然没有官方提供的那么完美,但已经很不错了

项目的GitHub地址:https://github.com/jasonmayes/Real-Time-Person-Removal
图一

(一)效果演示

看下官方的演示视频:
图二
我测试的:
图二

(二)代码

GitHub网站最近访问比较慢,这里我直接放上代码
index.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 andto 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>
</html>

stript.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');
}

style.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.* =============================================================================*//******************************************************* 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 {font-style: italic;color: #FF6F00;
}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;top: 0;left: 0;z-index: 2;
}#liveView {transform-origin: top left;transform: scale(1);
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/531483.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

codeforces C. Vanya and Scales

C. Vanya and ScalesVanya has a scales for weighing loads and weights of masses w0, w1, w2, ..., w100 grams where w is some integer not less than 2(exactly one weight of each nominal value). Vanya wonders whether he can weight an item with mass m using …

菱形继承和虚继承、对象模型和虚基表

1.菱形继承&#xff08;钻石继承&#xff09;&#xff1a;两个子类继承同一父类&#xff0c;而又有子类同时继承这两个子类。例如B,C两个类同时继承A&#xff0c;但是又有一个D类同时继承B,C类。 2.菱形继承的对象模型 class A { public:int _a; };class B :public A { p…

c++虚函数和虚函数表

前言 &#xff08;1&#xff09;虚基表与虚函数表是两个完全不同的概念 虚基表用来解决继承的二义性(虚基类可以解决)。虚函数用来实现泛型编程&#xff0c;运行时多态。 &#xff08;2&#xff09;虚函数是在基类普通函数前加virtual关键字&#xff0c;是实现多态的基础 &a…

VS2017安装配置Qt

这篇文章作为qt的开发环境配置篇&#xff0c;记录如何在vs2017中安装qt的 所需软件下载链接如下&#xff1a; QT下载链接&#xff1a;QT visual studio下载链接&#xff1a;visual studio 这里推荐安装最新的&#xff0c;原因是vs2017不支持一些老版本的makefile文件生成&#…

STM32位带区和位带别名区的浅谈

1.首先谈下为什么要使用位带&#xff1f; 在学习51单片机时就已经使用过位操作&#xff0c;比如使用sbit对单片机IO口的定义&#xff0c;但是STM32中并没有这类关键字&#xff0c;而是通过访问位带别名区来实现&#xff0c;即通过将每个比特位膨胀成一个32位字&#xff0c;当访…

Hibernate的数据查找,添加!

1.首先看一下测试数据库的物理模型 2.测试所需要的Hibernate的jar包 3.数据库的sql /**/ /* DBMS name: MySQL 5.0 */ /* Created on: 2015/7/3 23:17:57 */ /**/drop table if exists books;drop tab…

新手如何在Altium Designer中绘制电路板

好久没用AD画电路板了&#xff0c;这次电子实训让画个PCB板&#xff0c;借着这个机会写了一篇新手教程。 此教程所用的电路图是自动循迹小车&#xff0c;虽然元件比较简单&#xff0c;但是感觉还是很厉害的&#xff0c;一块看一下吧。 此教程仅适用于没有基础的同学 一、概述 …

Qt模仿QQ登录界面(一)

这两天研究qt&#xff0c;练习时做了个仿QQ登录界面&#xff0c;我这次实现的比较简单&#xff0c;先在这里记录一下&#xff0c;以后有空了会继续完善的。 &#xff08;一&#xff09;效果图 这里使用我的qq号测试的如图&#xff1a; &#xff08;二&#xff09;工程文件 &…

回流焊和波峰焊的区别

本文首先分别介绍回流焊和波峰焊的特点&#xff0c;然后对两者进行比较&#xff0c;欢迎评论补充哦~ 最近在实习看到了厂里面的回流焊的波峰焊&#xff0c;有点好奇就查了点资料&#xff0c;分享给同样爱学习的你。 一.回流焊 一般的表面贴装工艺分三步&#xff1a;印刷机施加…

三对角矩阵的压缩

三对角矩阵&#xff0c;从第二行开始选中的元素的个数都为3个。对于a[i,j]将要存储的位置k&#xff0c;首先前(i-1)行元素的个数是(i-2)*3 2(第一行元素的个数为2)&#xff0c;又a[i,j]属于第i行被选中元素的第j-i1个元素&#xff0c;所以k (i-2)*3 2 j-i1 2*ij-3 如果知道了…

LC和RC滤波电路分析

一、概述 整流电路的输出电压并不是纯粹的直流&#xff0c;从示波器观察整流电路的输出&#xff0c;与直流相差很大&#xff0c;波形中含有较大的脉动成分&#xff0c;称为纹波。为了获得比较理想的直流电压&#xff0c;需要利用具有储能作用的电抗性元件(如&#xff1a;电感、…

dev c++ Boost库的安装

dev c 的boost库的安装步骤 然后点击“check for updates”按钮 最后点击“Download selected”按钮&#xff0c;下载完成后安装.... 给dev添加boost库文件&#xff0c;找到之前安装的目录 #include<iostream> #include<string> #include<cstring> #include…

(一)C语言之数据类型

在这里主要讲了基本的知识&#xff0c;具体练习时注意用代码看看数据存储的位数和大小&#xff0c;像char a127;aa1;这时候a的值。可以用sizeof查看数据类型占的字节数。以及不同数据类型之间如何自动转换和强制转换&#xff0c;还有printf和scanf的具体用法&#xff0c;多动手…

十字链表的应用

#include<iostream> #include<cstring> #include<cstdio> #include<cstdlib> #define MAX_VERTEX_NUM 20 using namespace std; typedef struct ArcBox{int tailVex, headVex;//该弧的尾和头顶点的位置 struct ArcBox *hlink, *tlink;//分别为弧…

(二)C语言数据类型(2)

今天主要总结了一下运算符&#xff0c;详细介绍了运算符分类和优先级的基本知识 欢迎加入嵌入式学习群&#xff1a;559601187 运算符按操作数可以分为&#xff1a;单目运算符、双目运算符和三目运算符&#xff0c;优先级依次为单目运算符>双目运算符>三目运算符,在c语言里…

AOE网的关键路径的计算

求关键路径&#xff0c;只需理解顶点&#xff08;事件&#xff09;和边&#xff08;活动&#xff09;各自的两个特征属性以及求法即可&#xff1a; 先根据首结点的Ve(j)0由前向后&#xff08;正拓扑序列&#xff09;计算各顶点的最早发生时间 再根据终结点的Vl(j)等于它的V…

(三)C语言之九条语句

今天来说一下我们以后可能用的最多的C语言语句&#xff1a;条件语句、循环语句、控制语句。理论很简单&#xff0c;注重多自己写代码才能熟练运用。 欢迎加入嵌入式学习群&#xff1a;559601187 一起愉快的玩耍啊~ &#xff08;一&#xff09;条件语句 &#xff08;1&#xff…

次优查找树的建立

查找效率最高即平均查找长度最小&#xff0c;根据前面所学知识&#xff0c;我们可以给出有序表在非等概率情况下应遵循的两个原则&#xff1a; 1、最先访问的结点应是访问概率最大的结点&#xff1b; 2、每次访问应使结点两边尚未访问的结点的被访概率之和尽可能相等。 这两…

平衡二叉树AVL插入

平衡二叉树(Balancedbinary tree)是由阿德尔森-维尔斯和兰迪斯(Adelson-Velskiiand Landis)于1962年首先提出的&#xff0c;所以又称为AVL树。 定义&#xff1a;平衡二叉树或为空树,或为如下性质的二叉排序树: &#xff08;1&#xff09;左右子树深度之差的绝对值不超过1; &…

(五)C语言之二维数组

今天的第二个内容单独拿出来讲一下&#xff0c;对于初接触C语言的人来说&#xff0c;这个知识点比较难懂&#xff0c;后面在讲指针的时候我还会提到这部分的内容&#xff0c;看不懂的同学可以看后面的内容。 指针变量可以指向一维数组中的元素&#xff0c;当然也就可以指向二维…