├── LICENCE
├── README.md
├── index.html
├── script.js
├── script_original.js
└── style.css
/LICENCE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Disappearing-People - Person removal from complex backgrounds over time.
2 | Removing people from complex backgrounds in real time using TensorFlow.js in the web browser using JavaScript.
3 |
4 | ## What can this do?
5 |
6 | This code attempts to learn over time the makeup of the background of a video such that I can attempt to remove any humans from the scene. This is all happening in real time, in the browser, using TensorFlow.js. #MadeWithTFJS
7 |
8 | This is an experiment. It may not be perfect in all situations.
9 |
10 | 
11 |
12 |
13 | ## Live Demos
14 |
15 | Go ahead and try it right now in your own web browser. Pick your preference and give me a fork / like :-)
16 |
17 | Codepen.io: https://codepen.io/jasonmayes/pen/GRJqgma
18 |
19 | Glitch.com: https://glitch.com/~disappearing-people
20 |
21 |
22 | ## Usage
23 |
24 | Feel free to use in your own projects. Code is released under Apache licence. If you decide to use my code please consider giving me a shout out! Would love to see what others create with it :-) Thanks.
25 |
26 | ---
27 |
--------------------------------------------------------------------------------
/index.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 | <!-- Import the webpage's stylesheet -->
11 | <link rel="stylesheet" href="style.css">
12 |
13 | <!-- Import TensorFlow.js library -->
14 | <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js" type="text/javascript"></script>
15 | </head>
16 | <body>
17 | <h1>Disappearing People Project</h1>
18 |
19 | <header class="note">
20 | <h2>Removing people from complex backgrounds in real time using TensorFlow.js</h2>
21 | </header>
22 |
23 | <h2>How to use</h2>
24 | <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>
25 | <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>
26 | <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>
27 | <section id="demos" class="invisible">
28 |
29 | <h2>Demo: Webcam live removal</h2>
30 | <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>
31 |
32 | <div id="liveView" class="webcam">
33 | <button id="webcamButton">Enable Webcam</button>
34 | <video id="webcam" autoplay></video>
35 | </div>
36 | </section>
37 |
38 |
39 | <!-- Include the Glitch button to show what the webpage is about and
40 | to make it easier for folks to view source and remix -->
41 | <div class="glitchButton" style="position:fixed;top:20px;right:20px;"></div>
42 | <script src="https://button.glitch.me/button.js"></script>
43 |
44 | <!-- Load the bodypix model to recognize body parts in images -->
45 | <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/body-pix@2.0"></script>
46 |
47 | <!-- Import the page's JavaScript to do some stuff -->
48 | <script src="script.js" defer></script>
49 | </body>
50 | </html>
--------------------------------------------------------------------------------
/script.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 |
29 | const video = document.getElementById('webcam');
30 | const liveView = document.getElementById('liveView');
31 | const demosSection = document.getElementById('demos');
32 | const DEBUG = false;
33 |
34 |
35 | // An object to configure parameters to set for the bodypix model.
36 | // See github docs for explanations.
37 | const bodyPixProperties = {
38 | architecture: 'MobileNetV1',
39 | outputStride: 16,
40 | multiplier: 0.75,
41 | quantBytes: 4
42 | };
43 |
44 | // An object to configure parameters for detection. I have raised
45 | // the segmentation threshold to 90% confidence to reduce the
46 | // number of false positives.
47 | const segmentationProperties = {
48 | flipHorizontal: false,
49 | internalResolution: 'high',
50 | segmentationThreshold: 0.9,
51 | scoreThreshold: 0.2
52 | };
53 |
54 |
55 | // Render returned segmentation data to a given canvas context.
56 | function processSegmentation(canvas, segmentation) {
57 | var ctx = canvas.getContext('2d');
58 | console.log(segmentation)
59 | // Get data from our overlay canvas which is attempting to estimate background.
60 | var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
61 | var data = imageData.data;
62 |
63 | // Get data from the live webcam view which has all data.
64 | var liveData = videoRenderCanvasCtx.getImageData(0, 0, canvas.width, canvas.height);
65 | var dataL = liveData.data;
66 |
67 | var minX = 100000;
68 | var minY = 100000;
69 | var maxX = 0;
70 | var maxY = 0;
71 |
72 | var foundBody = false;
73 |
74 | // Go through pixels and figure out bounding box of body pixels.
75 | for (let x = 0; x < canvas.width; x++) {
76 | for (let y = 0; y < canvas.height; y++) {
77 | let n = y * canvas.width + x;
78 | // Human pixel found. Update bounds.
79 | if (segmentation.data[n] !== 0) {
80 | if(x < minX) {
81 | minX = x;
82 | }
83 |
84 | if(y < minY) {
85 | minY = y;
86 | }
87 |
88 | if(x > maxX) {
89 | maxX = x;
90 | }
91 |
92 | if(y > maxY) {
93 | maxY = y;
94 | }
95 | foundBody = true;
96 | }
97 | }
98 | }
99 |
100 | // Calculate dimensions of bounding box.
101 | var width = maxX - minX;
102 | var height = maxY - minY;
103 |
104 | // Define scale factor to use to allow for false negatives around this region.
105 | var scale = 1.3;
106 |
107 | // Define scaled dimensions.
108 | var newWidth = width * scale;
109 | var newHeight = height * scale;
110 |
111 | // Caculate the offset to place new bounding box so scaled from center of current bounding box.
112 | var offsetX = (newWidth - width) / 2;
113 | var offsetY = (newHeight - height) / 2;
114 |
115 | var newXMin = minX - offsetX;
116 | var newYMin = minY - offsetY;
117 |
118 |
119 | // Now loop through update backgound understanding with new data
120 | // if not inside a bounding box.
121 | for (let x = 0; x < canvas.width; x++) {
122 | for (let y = 0; y < canvas.height; y++) {
123 | // If outside bounding box and we found a body, update background.
124 | if (foundBody && (x < newXMin || x > newXMin + newWidth) || ( y < newYMin || y > newYMin + newHeight)) {
125 | // Convert xy co-ords to array offset.
126 | let n = y * canvas.width + x;
127 |
128 | data[n * 4] = dataL[n * 4];
129 | data[n * 4 + 1] = dataL[n * 4 + 1];
130 | data[n * 4 + 2] = dataL[n * 4 + 2];
131 | data[n * 4 + 3] = 255;
132 |
133 | } else if (!foundBody) {
134 | // No body found at all, update all pixels.
135 | let n = y * canvas.width + x;
136 | data[n * 4] = dataL[n * 4];
137 | data[n * 4 + 1] = dataL[n * 4 + 1];
138 | data[n * 4 + 2] = dataL[n * 4 + 2];
139 | data[n * 4 + 3] = 255;
140 | }
141 | }
142 | }
143 |
144 | ctx.putImageData(imageData, 0, 0);
145 |
146 | if (DEBUG) {
147 | ctx.strokeStyle = "#00FF00"
148 | ctx.beginPath();
149 | ctx.rect(newXMin, newYMin, newWidth, newHeight);
150 | ctx.stroke();
151 | }
152 | }
153 |
154 |
155 |
156 | // Let's load the model with our parameters defined above.
157 | // Before we can use bodypix class we must wait for it to finish
158 | // loading. Machine Learning models can be large and take a moment to
159 | // get everything needed to run.
160 | var modelHasLoaded = false;
161 | var model = undefined;
162 |
163 | model = bodyPix.load(bodyPixProperties).then(function (loadedModel) {
164 | model = loadedModel;
165 | modelHasLoaded = true;
166 | // Show demo section now model is ready to use.
167 | demosSection.classList.remove('invisible');
168 | });
169 |
170 |
171 | /********************************************************************
172 | // Continuously grab image from webcam stream and classify it.
173 | ********************************************************************/
174 |
175 | var previousSegmentationComplete = true;
176 |
177 | // Check if webcam access is supported.
178 | function hasGetUserMedia() {
179 | return !!(navigator.mediaDevices &&
180 | navigator.mediaDevices.getUserMedia);
181 | }
182 |
183 |
184 | // This function will repeatidly call itself when the browser is ready to process
185 | // the next frame from webcam.
186 | function predictWebcam() {
187 | if (previousSegmentationComplete) {
188 | // Copy the video frame from webcam to a tempory canvas in memory only (not in the DOM).
189 | videoRenderCanvasCtx.drawImage(video, 0, 0);
190 | previousSegmentationComplete = false;
191 | // Now classify the canvas image we have available.
192 | model.segmentPerson(videoRenderCanvas, segmentationProperties).then(function(segmentation) {
193 | processSegmentation(webcamCanvas, segmentation);
194 | previousSegmentationComplete = true;
195 | });
196 | }
197 |
198 | // Call this function again to keep predicting when the browser is ready.
199 | window.requestAnimationFrame(predictWebcam);
200 | }
201 |
202 |
203 | // Enable the live webcam view and start classification.
204 | function enableCam(event) {
205 | if (!modelHasLoaded) {
206 | return;
207 | }
208 |
209 | // Hide the button.
210 | event.target.classList.add('removed');
211 |
212 | // getUsermedia parameters.
213 | const constraints = {
214 | video: true
215 | };
216 |
217 | // Activate the webcam stream.
218 | navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
219 | video.addEventListener('loadedmetadata', function() {
220 | // Update widths and heights once video is successfully played otherwise
221 | // it will have width and height of zero initially causing classification
222 | // to fail.
223 | webcamCanvas.width = video.videoWidth;
224 | webcamCanvas.height = video.videoHeight;
225 | videoRenderCanvas.width = video.videoWidth;
226 | videoRenderCanvas.height = video.videoHeight;
227 | bodyPixCanvas.width = video.videoWidth;
228 | bodyPixCanvas.height = video.videoHeight;
229 | let webcamCanvasCtx = webcamCanvas.getContext('2d');
230 | webcamCanvasCtx.drawImage(video, 0, 0);
231 | });
232 |
233 | video.srcObject = stream;
234 |
235 | video.addEventListener('loadeddata', predictWebcam);
236 | });
237 | }
238 |
239 |
240 | // We will create a tempory canvas to render to store frames from
241 | // the web cam stream for classification.
242 | var videoRenderCanvas = document.createElement('canvas');
243 | var videoRenderCanvasCtx = videoRenderCanvas.getContext('2d');
244 |
245 | // Lets create a canvas to render our findings to the DOM.
246 | var webcamCanvas = document.createElement('canvas');
247 | webcamCanvas.setAttribute('class', 'overlay');
248 | liveView.appendChild(webcamCanvas);
249 |
250 | // Create a canvas to render ML findings from to manipulate.
251 | var bodyPixCanvas = document.createElement('canvas');
252 | bodyPixCanvas.setAttribute('class', 'overlay');
253 | var bodyPixCanvasCtx = bodyPixCanvas.getContext('2d');
254 | bodyPixCanvasCtx.fillStyle = '#FF0000';
255 |
256 | liveView.appendChild(bodyPixCanvas);
257 |
258 | // If webcam supported, add event listener to button for when user
259 | // wants to activate it.
260 | if (hasGetUserMedia()) {
261 | const enableWebcamButton = document.getElementById('webcamButton');
262 | enableWebcamButton.addEventListener('click', enableCam);
263 | } else {
264 | console.warn('getUserMedia() is not supported by your browser');
265 | }
266 |
--------------------------------------------------------------------------------
/script_original.js:
--------------------------------------------------------------------------------
1 |
2 | /**
3 | * @license
4 | * Copyright 2018 Google LLC. All Rights Reserved.
5 | * Licensed under the Apache License, Version 2.0 (the "License");
6 | * you may not use this file except in compliance with the License.
7 | * You may obtain a copy of the License at
8 | *
9 | * http://www.apache.org/licenses/LICENSE-2.0
10 | *
11 | * Unless required by applicable law or agreed to in writing, software
12 | * distributed under the License is distributed on an "AS IS" BASIS,
13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 | * See the License for the specific language governing permissions and
15 | * limitations under the License.
16 | * =============================================================================
17 | */
18 |
19 | /********************************************************************
20 | * Real-Time-Person-Removal Created by Jason Mayes 2020.
21 | *
22 | * Get latest code on my Github:
23 | * https://github.com/jasonmayes/Real-Time-Person-Removal
24 | *
25 | * Got questions? Reach out to me on social:
26 | * Twitter: @jason_mayes
27 | * LinkedIn: https://www.linkedin.com/in/creativetech
28 | ********************************************************************/
29 |
30 | const video = document.getElementById('webcam');
31 | const liveView = document.getElementById('liveView');
32 | const demosSection = document.getElementById('demos');
33 | const DEBUG = false;
34 |
35 |
36 | // An object to configure parameters to set for the bodypix model.
37 | // See github docs for explanations.
38 | const bodyPixProperties = {
39 | architecture: 'MobileNetV1',
40 | outputStride: 16,
41 | multiplier: 0.75,
42 | quantBytes: 4
43 | };
44 |
45 | // An object to configure parameters for detection. I have raised
46 | // the segmentation threshold to 90% confidence to reduce the
47 | // number of false positives.
48 | const segmentationProperties = {
49 | flipHorizontal: false,
50 | internalResolution: 'high',
51 | segmentationThreshold: 0.9
52 | };
53 |
54 |
55 | // Must be even. The size of square we wish to search for body parts.
56 | // This is the smallest area that will render/not render depending on
57 | // if a body part is found in that square.
58 | const SEARCH_RADIUS = 300;
59 | const SEARCH_OFFSET = SEARCH_RADIUS / 2;
60 |
61 | // RESOLUTION_MIN should be smaller than SEARCH RADIUS. About 10x smaller seems to
62 | // work well. Effects overlap in search space to clean up body overspill for things
63 | // that were not classified as body but infact were.
64 | const RESOLUTION_MIN = 20;
65 |
66 | // Render returned segmentation data to a given canvas context.
67 | function processSegmentation(canvas, segmentation) {
68 | var ctx = canvas.getContext('2d');
69 |
70 | // Get data from our overlay canvas which is attempting to estimate background.
71 | var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
72 | var data = imageData.data;
73 |
74 | // Get data from the live webcam view which has all data.
75 | var liveData = videoRenderCanvasCtx.getImageData(0, 0, canvas.width, canvas.height);
76 | var dataL = liveData.data;
77 |
78 | // Now loop through and see if pixels contain human parts. If not, update
79 | // backgound understanding with new data.
80 | for (let x = RESOLUTION_MIN; x < canvas.width; x += RESOLUTION_MIN) {
81 | for (let y = RESOLUTION_MIN; y < canvas.height; y += RESOLUTION_MIN) {
82 | // Convert xy co-ords to array offset.
83 | let n = y * canvas.width + x;
84 |
85 | let foundBodyPartNearby = false;
86 |
87 | // Let's check around a given pixel if any other pixels were body like.
88 | let yMin = y - SEARCH_OFFSET;
89 | yMin = yMin < 0 ? 0: yMin;
90 |
91 | let yMax = y + SEARCH_OFFSET;
92 | yMax = yMax > canvas.height ? canvas.height : yMax;
93 |
94 | let xMin = x - SEARCH_OFFSET;
95 | xMin = xMin < 0 ? 0: xMin;
96 |
97 | let xMax = x + SEARCH_OFFSET;
98 | xMax = xMax > canvas.width ? canvas.width : xMax;
99 |
100 | for (let i = xMin; i < xMax; i++) {
101 | for (let j = yMin; j < yMax; j++) {
102 |
103 | let offset = j * canvas.width + i;
104 | // If any of the pixels in the square we are analysing has a body
105 | // part, mark as contaminated.
106 | if (segmentation.data[offset] !== 0) {
107 | foundBodyPartNearby = true;
108 | break;
109 | }
110 | }
111 | }
112 |
113 | // Update patch if patch was clean.
114 | if (!foundBodyPartNearby) {
115 | for (let i = xMin; i < xMax; i++) {
116 | for (let j = yMin; j < yMax; j++) {
117 | // Convert xy co-ords to array offset.
118 | let offset = j * canvas.width + i;
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 | data[offset * 4] = 255;
134 | data[offset * 4 + 1] = 0;
135 | data[offset * 4 + 2] = 0;
136 | data[offset * 4 + 3] = 255;
137 | }
138 | }
139 | }
140 | }
141 |
142 | }
143 | }
144 | ctx.putImageData(imageData, 0, 0);
145 | }
146 |
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.
153 | var modelHasLoaded = false;
154 | var model = undefined;
155 |
156 | model = 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 | /********************************************************************
165 | // Continuously grab image from webcam stream and classify it.
166 | ********************************************************************/
167 |
168 | var previousSegmentationComplete = true;
169 |
170 | // Check if webcam access is supported.
171 | function hasGetUserMedia() {
172 | return !!(navigator.mediaDevices &&
173 | navigator.mediaDevices.getUserMedia);
174 | }
175 |
176 |
177 | // This function will repeatidly call itself when the browser is ready to process
178 | // the next frame from webcam.
179 | function predictWebcam() {
180 | if (previousSegmentationComplete) {
181 | // Copy the video frame from webcam to a tempory canvas in memory only (not in the DOM).
182 | videoRenderCanvasCtx.drawImage(video, 0, 0);
183 | previousSegmentationComplete = false;
184 | // Now classify the canvas image we have available.
185 | model.segmentPerson(videoRenderCanvas, segmentationProperties).then(function(segmentation) {
186 | processSegmentation(webcamCanvas, segmentation);
187 | previousSegmentationComplete = true;
188 | });
189 | }
190 |
191 | // Call this function again to keep predicting when the browser is ready.
192 | window.requestAnimationFrame(predictWebcam);
193 | }
194 |
195 |
196 | // Enable the live webcam view and start classification.
197 | function enableCam(event) {
198 | if (!modelHasLoaded) {
199 | return;
200 | }
201 |
202 | // Hide the button.
203 | event.target.classList.add('removed');
204 |
205 | // getUsermedia parameters.
206 | const constraints = {
207 | video: true
208 | };
209 |
210 | // Activate the webcam stream.
211 | navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
212 | video.addEventListener('loadedmetadata', function() {
213 | // Update widths and heights once video is successfully played otherwise
214 | // it will have width and height of zero initially causing classification
215 | // to fail.
216 | webcamCanvas.width = video.videoWidth;
217 | webcamCanvas.height = video.videoHeight;
218 | videoRenderCanvas.width = video.videoWidth;
219 | videoRenderCanvas.height = video.videoHeight;
220 | let webcamCanvasCtx = webcamCanvas.getContext('2d');
221 | webcamCanvasCtx.drawImage(video, 0, 0);
222 | });
223 |
224 | video.srcObject = stream;
225 |
226 | video.addEventListener('loadeddata', predictWebcam);
227 | });
228 | }
229 |
230 |
231 | // We will create a tempory canvas to render to store frames from
232 | // the web cam stream for classification.
233 | var videoRenderCanvas = document.createElement('canvas');
234 | var videoRenderCanvasCtx = videoRenderCanvas.getContext('2d');
235 |
236 | // Lets create a canvas to render our findings to the DOM.
237 | var webcamCanvas = document.createElement('canvas');
238 | webcamCanvas.setAttribute('class', 'overlay');
239 | liveView.appendChild(webcamCanvas);
240 |
241 | // If webcam supported, add event listener to button for when user
242 | // wants to activate it.
243 | if (hasGetUserMedia()) {
244 | const enableWebcamButton = document.getElementById('webcamButton');
245 | enableWebcamButton.addEventListener('click', enableCam);
246 | } else {
247 | console.warn('getUserMedia() is not supported by your browser');
248 | }
249 |
--------------------------------------------------------------------------------
/style.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 | * Stylesheet by Jason Mayes 2020.
21 | *
22 | * Get latest code on my Github:
23 | * https://github.com/jasonmayes/Real-Time-Person-Removal
24 | * Got questions? Reach out to me on social:
25 | * Twitter: @jason_mayes
26 | * LinkedIn: https://www.linkedin.com/in/creativetech
27 | *****************************************************/
28 |
29 | body {
30 | font-family: helvetica, arial, sans-serif;
31 | margin: 2em;
32 | color: #3D3D3D;
33 | }
34 |
35 | h1 {
36 | font-style: italic;
37 | color: #FF6F00;
38 | }
39 |
40 | h2 {
41 | clear: both;
42 | }
43 |
44 | em {
45 | font-weight: bold;
46 | }
47 |
48 | video {
49 | clear: both;
50 | display: block;
51 | }
52 |
53 | section {
54 | opacity: 1;
55 | transition: opacity 500ms ease-in-out;
56 | }
57 |
58 | header, footer {
59 | clear: both;
60 | }
61 |
62 | button {
63 | z-index: 1000;
64 | position: relative;
65 | }
66 |
67 | .removed {
68 | display: none;
69 | }
70 |
71 | .invisible {
72 | opacity: 0.2;
73 | }
74 |
75 | .note {
76 | font-style: italic;
77 | font-size: 130%;
78 | }
79 |
80 | .webcam {
81 | position: relative;
82 | }
83 |
84 | .webcam, .classifyOnClick {
85 | position: relative;
86 | float: left;
87 | width: 48%;
88 | margin: 2% 1%;
89 | cursor: pointer;
90 | }
91 |
92 | .webcam p, .classifyOnClick p {
93 | position: absolute;
94 | padding: 5px;
95 | background-color: rgba(255, 111, 0, 0.85);
96 | color: #FFF;
97 | border: 1px dashed rgba(255, 255, 255, 0.7);
98 | z-index: 2;
99 | font-size: 12px;
100 | }
101 |
102 | .highlighter {
103 | background: rgba(0, 255, 0, 0.25);
104 | border: 1px dashed #fff;
105 | z-index: 1;
106 | position: absolute;
107 | }
108 |
109 | .classifyOnClick {
110 | z-index: 0;
111 | position: relative;
112 | }
113 |
114 | .classifyOnClick canvas, .webcam canvas.overlay {
115 | opacity: 1;
116 |
117 | top: 0;
118 | left: 0;
119 | z-index: 2;
120 | }
121 |
122 | #liveView {
123 | transform-origin: top left;
124 | transform: scale(1);
125 | }
126 |
--------------------------------------------------------------------------------