From c26eed54ab4fa2744555548d0cfbca003a73bfc6 Mon Sep 17 00:00:00 2001 From: "Glitch (stitch-jasper-road)" Date: Fri, 14 Oct 2022 01:22:31 +0000 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=86=F0=9F=9A=8F=20Updated=20with=20Gli?= =?UTF-8?q?tch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .glitch-assets | 20 +++++ LICENSE.md | 201 +++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 53 ++++++++++++- index.html | 32 ++++++++ script.js | 129 +++++++++++++++++++++++++++++++ style.css | 71 +++++++++++++++++ 6 files changed, 505 insertions(+), 1 deletion(-) create mode 100644 .glitch-assets create mode 100644 LICENSE.md create mode 100644 index.html create mode 100644 script.js create mode 100644 style.css diff --git a/.glitch-assets b/.glitch-assets new file mode 100644 index 0000000..48800e9 --- /dev/null +++ b/.glitch-assets @@ -0,0 +1,20 @@ +{"name":"drag-in-files.svg","date":"2016-10-22T16:17:49.954Z","url":"https://cdn.hyperdev.com/drag-in-files.svg","type":"image/svg","size":7646,"imageWidth":276,"imageHeight":276,"thumbnail":"https://cdn.hyperdev.com/drag-in-files.svg","thumbnailWidth":276,"thumbnailHeight":276,"dominantColor":"rgb(102, 153, 205)","uuid":"adSBq97hhhpFNUna"} +{"name":"click-me.svg","date":"2016-10-23T16:17:49.954Z","url":"https://cdn.hyperdev.com/click-me.svg","type":"image/svg","size":7116,"imageWidth":276,"imageHeight":276,"thumbnail":"https://cdn.hyperdev.com/click-me.svg","thumbnailWidth":276,"thumbnailHeight":276,"dominantColor":"rgb(243, 185, 186)","uuid":"adSBq97hhhpFNUnb"} +{"name":"paste-me.svg","date":"2016-10-24T16:17:49.954Z","url":"https://cdn.hyperdev.com/paste-me.svg","type":"image/svg","size":7242,"imageWidth":276,"imageHeight":276,"thumbnail":"https://cdn.hyperdev.com/paste-me.svg","thumbnailWidth":276,"thumbnailHeight":276,"dominantColor":"rgb(42, 179, 185)","uuid":"adSBq97hhhpFNUnc"} +{"uuid":"adSBq97hhhpFNUna","deleted":true} +{"uuid":"adSBq97hhhpFNUnb","deleted":true} +{"uuid":"adSBq97hhhpFNUnc","deleted":true} +{"name":"dog_flickr_publicdomain.jpg","date":"2020-01-16T21:16:36.930Z","url":"https://cdn.glitch.com/5bf7c54b-c36f-4009-a191-186909fb788e%2Fdog_flickr_publicdomain.jpg","type":"image/jpeg","size":15419,"imageWidth":400,"imageHeight":267,"thumbnail":"https://cdn.glitch.com/5bf7c54b-c36f-4009-a191-186909fb788e%2Fthumbnails%2Fdog_flickr_publicdomain.jpg","thumbnailWidth":330,"thumbnailHeight":221,"uuid":"EtCdpyjjAajTrdf3"} +{"name":"cat_flickr_publicdomain.jpg","date":"2020-01-16T22:57:24.151Z","url":"https://cdn.glitch.com/5bf7c54b-c36f-4009-a191-186909fb788e%2Fcat_flickr_publicdomain.jpg","type":"image/jpeg","size":36382,"imageWidth":400,"imageHeight":267,"thumbnail":"https://cdn.glitch.com/5bf7c54b-c36f-4009-a191-186909fb788e%2Fthumbnails%2Fcat_flickr_publicdomain.jpg","thumbnailWidth":330,"thumbnailHeight":221,"uuid":"rf1siYMZKUqs0Zx0"} +{"name":"dogs_flickr_publicdomain.jpg","date":"2020-01-17T20:48:42.737Z","url":"https://cdn.glitch.com/74418d0b-3465-49a2-8c71-a721b7734473%2Fdogs_flickr_publicdomain.jpg","type":"image/jpeg","size":34972,"imageWidth":400,"imageHeight":250,"thumbnail":"https://cdn.glitch.com/74418d0b-3465-49a2-8c71-a721b7734473%2Fthumbnails%2Fdogs_flickr_publicdomain.jpg","thumbnailWidth":330,"thumbnailHeight":207,"uuid":"34Hs2Sf89iVKGaso"} +{"uuid":"34Hs2Sf89iVKGaso","deleted":true} +{"name":"dogs_flickr_publicdomain.jpg","date":"2020-01-17T20:55:14.974Z","url":"https://cdn.glitch.com/74418d0b-3465-49a2-8c71-a721b7734473%2Fdogs_flickr_publicdomain.jpg","type":"image/jpeg","size":56688,"imageWidth":400,"imageHeight":334,"thumbnail":"https://cdn.glitch.com/74418d0b-3465-49a2-8c71-a721b7734473%2Fthumbnails%2Fdogs_flickr_publicdomain.jpg","thumbnailWidth":330,"thumbnailHeight":276,"uuid":"ETF7NEHYJs1MoaT4"} +{"name":"cats_flickr_publicdomain.jpg","date":"2020-01-17T20:59:13.947Z","url":"https://cdn.glitch.com/74418d0b-3465-49a2-8c71-a721b7734473%2Fcats_flickr_publicdomain.jpg","type":"image/jpeg","size":48855,"imageWidth":400,"imageHeight":300,"thumbnail":"https://cdn.glitch.com/74418d0b-3465-49a2-8c71-a721b7734473%2Fthumbnails%2Fcats_flickr_publicdomain.jpg","thumbnailWidth":330,"thumbnailHeight":248,"uuid":"Tbm0xSxEx3GqPAVg"} +{"name":"coupledog.jpg","date":"2020-06-04T22:53:27.769Z","url":"https://cdn.glitch.com/74418d0b-3465-49a2-8c71-a721b7734473%2Fcoupledog.jpg","type":"image/jpeg","size":5985848,"imageWidth":6000,"imageHeight":4000,"thumbnail":"https://cdn.glitch.com/74418d0b-3465-49a2-8c71-a721b7734473%2Fthumbnails%2Fcoupledog.jpg","thumbnailWidth":330,"thumbnailHeight":220,"uuid":"Zw3KmbfXtjxgsRHT"} +{"uuid":"Zw3KmbfXtjxgsRHT","deleted":true} +{"name":"coupledog.jpg","date":"2020-06-04T22:56:35.128Z","url":"https://cdn.glitch.com/74418d0b-3465-49a2-8c71-a721b7734473%2Fcoupledog.jpg","type":"image/jpeg","size":320255,"imageWidth":800,"imageHeight":765,"thumbnail":"https://cdn.glitch.com/74418d0b-3465-49a2-8c71-a721b7734473%2Fthumbnails%2Fcoupledog.jpg","thumbnailWidth":330,"thumbnailHeight":316,"uuid":"qGrCBhZHDEifDWdi"} +{"uuid":"qGrCBhZHDEifDWdi","deleted":true} +{"name":"coupledog.jpg","date":"2020-06-04T22:59:12.891Z","url":"https://cdn.glitch.com/74418d0b-3465-49a2-8c71-a721b7734473%2Fcoupledog.jpg","type":"image/jpeg","size":76387,"imageWidth":370,"imageHeight":334,"thumbnail":"https://cdn.glitch.com/74418d0b-3465-49a2-8c71-a721b7734473%2Fthumbnails%2Fcoupledog.jpg","thumbnailWidth":330,"thumbnailHeight":298,"uuid":"9bHLMhw9Q00qiYIy"} +{"name":"doggo.jpg","date":"2020-06-16T00:18:05.530Z","url":"https://cdn.glitch.com/74418d0b-3465-49a2-8c71-a721b7734473%2Fdoggo.jpg","type":"image/jpeg","size":141005,"imageWidth":2250,"imageHeight":1500,"thumbnail":"https://cdn.glitch.com/74418d0b-3465-49a2-8c71-a721b7734473%2Fthumbnails%2Fdoggo.jpg","thumbnailWidth":330,"thumbnailHeight":220,"uuid":"qxL5mTC9HZLWwvj7"} +{"uuid":"qxL5mTC9HZLWwvj7","deleted":true} +{"name":"doggo.jpg","date":"2020-06-16T00:18:45.716Z","url":"https://cdn.glitch.com/74418d0b-3465-49a2-8c71-a721b7734473%2Fdoggo.jpg","type":"image/jpeg","size":45320,"imageWidth":640,"imageHeight":427,"thumbnail":"https://cdn.glitch.com/74418d0b-3465-49a2-8c71-a721b7734473%2Fthumbnails%2Fdoggo.jpg","thumbnailWidth":330,"thumbnailHeight":221,"uuid":"Jz6rixUJnkLQf7Ew"} diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..a4b955b --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2020 Jason Mayes + + 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. diff --git a/README.md b/README.md index 1b07db6..9b60e2d 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,53 @@ -# proyectos-eventos +# Detección de múltiples objetos utilizando un modelo pre-entrenado en TensorFlow.js +## Dificultad: Fácil + +Nota: Esta demostración carga una clase de JavaScript fácil de usar hecha por el equipo de TensorFlow.js para hacer el trabajo duro por ti, por lo que no se necesita ningún conocimiento de Machine Learning para usarlo. + +Si quieres aprender a cargar directamente un modelo guardado en TensorFlow.js, consulta nuestro tutorial sobre la carga de modelos TensorFlow.js. + +Si quieres entrenar un sistema para reconocer tus propios objetos, usando tus propios datos, entonces consulta nuestros tutoriales sobre "aprendizaje de transferencia". + +## ¿Qué puede hacer este demo? + +Esta demostración muestra cómo podemos utilizar una solución de Machine Learning pre-entrenada para reconocer múltiples objetos (sí, ¡más de uno a la vez!) en cualquier imagen que deseemos presentarle. Y lo que es mejor, no sólo sabemos que la imagen contiene un objeto, sino que también podemos obtener las coordenadas del cuadro delimitador de cada objeto que encuentra, lo que le permite resaltar el objeto encontrado en la imagen. + +Para esta demostración estamos cargando un modelo utilizando la arquitectura ImageNet-SSD, para [reconocer 90 objetos comunes](https://github.com/tensorflow/tfjs-models/blob/master/coco-ssd/src/classes.ts) que ya ha sido enseñado a encontrar a partir del [conjunto de datos COCO](http://cocodataset.org/#home). + +Si lo que quieres reconocer está en esa lista de cosas que conoce (por ejemplo un gato, un perro, etc.), esto puede serte útil tal cual en tus propios proyectos, o simplemente para experimentar con el Machine Learning en el navegador y familiarizarte con las posibilidades del aprendizaje automático. + +Si te sientes especialmente confiada, puedes consultar nuestra [documentación de GitHub](https://github.com/tensorflow/tfjs-models/tree/master/coco-ssd) que entra en mucho más detalle para personalizar varios parámetros para adaptar el rendimiento a tus necesidades. + +## ¿Qué hay en los archivos? + +### ← index.html + +Simplemente tenemos algunas etiquetas de script en nuestro HTML para tomar la última versión de TensorFlow.js y la clase de modelo de Machine Learning que puede tomar los datos de la imagen como entrada y las predicciones de salida para lo que ve en esos datos de la imagen. + +En este caso simplemente hacemos referencia a lo siguiente para cargar TensorFlow.js: + +```HTML + +``` + +Sin embargo, si quieres cargar una versión concreta de TensorFlow.js puedes hacerlo así: + +```HTML + +``` + +Finalmente verás que cargamos la clase del modelo de aprendizaje automático que luego usaremos en script.js de esta manera: + +```HTML + +``` + +### ← style.css + +No hay nada que ver aquí. Sólo estilos para hacer que la demo se vea más bonita. Puedes usarlos o ignorarlos a tu gusto. + +### ← script.js + +Este archivo muestra el código de demostración que necesitas escribir en JavaScript para interactuar con la clase COCO-SSD que importamos en el HTML. Aquí es donde ocurre la magia. Podemos pasar datos a la clase y luego recuperar las predicciones sobre lo que piensa que vio en la imagen que luego podemos utilizar para tomar una decisión. El archivo está bien comentado, así que lee los comentarios para saber más. Se proporcionan demostraciones para las imágenes en el DOM y también para la clasificación del flujo de la cámara web en vivo. + +--- diff --git a/index.html b/index.html new file mode 100644 index 0000000..d200c8c --- /dev/null +++ b/index.html @@ -0,0 +1,32 @@ + + + + Detección de múltiples objetos utilizando un modelo pre-entrenado en TensorFlow.js + + + + + +

Detección de múltiples objetos utilizando un modelo pre-entrenado en TensorFlow.js

+ +

Espera a que el modelo se cargue antes de hacer clic en el botón para habilitar la cámara web, momento en el que será visible para su uso.

+ + + + + + + + + + + + \ No newline at end of file diff --git a/script.js b/script.js new file mode 100644 index 0000000..916c01e --- /dev/null +++ b/script.js @@ -0,0 +1,129 @@ +/** + * @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. + * ============================================================================= + */ + +const video = document.getElementById('webcam'); +const liveView = document.getElementById('liveView'); +const demosSection = document.getElementById('demos'); +const enableWebcamButton = document.getElementById('webcamButton'); + +// Comprueba si el acceso a la cámara web es compatible. +function getUserMediaSupported() { + return !!(navigator.mediaDevices && + navigator.mediaDevices.getUserMedia); +} + +// Si se admite la cámara web, añadir un receptor de eventos al botón para que cuando el usuario +// quiera activarlo para llamar a la función enableCam que +// definiremos en el siguiente paso. +if (getUserMediaSupported()) { + enableWebcamButton.addEventListener('click', enableCam); +} else { + console.warn('getUserMedia() is not supported by your browser'); +} + +// Placeholder de función para el próximo paso. Pegar sobre esto en el siguiente paso. +function enableCam(event) { +} + + +// Habilitar la vista de la cámara web en vivo y comenzar la clasificación. +function enableCam(event) { + // Sólo continúa si el COCO-SSD ha terminado de cargarse. + if (!model) { + return; + } + + // Ocultar el botón una vez pulsado. + event.target.classList.add('removed'); + + // Parámetros getUsermedia para forzar el vídeo pero no el audio. + const constraints = { + video: true + }; + + // Activar el flujo de video de la webcam. + navigator.mediaDevices.getUserMedia(constraints).then(function(stream) { + video.srcObject = stream; + video.addEventListener('loadeddata', predictWebcam); + }); +} + +// Placeholder de función para el próximo paso. +function predictWebcam() { +} + +// Finge que el modelo se ha cargado para que podamos probar el código de la webcam. +var model = true; +demosSection.classList.remove('invisible'); + +// Almacenar el modelo resultante en el ámbito global de nuestra aplicación. +var model = undefined; + +// Antes de poder utilizar la clase COCO-SSD debemos esperar a que termine de +// cargar. Los modelos de Machine Learning pueden ser grandes y tardan un momento +// para obtener todo lo necesario para su ejecución. +// Nota: cocoSsd es un objeto externo cargado desde nuestro index.html +// importación de etiquetas de script, así que ignora cualquier advertencia en Glitch. +cocoSsd.load().then(function (loadedModel) { + model = loadedModel; + // Mostrar la sección de demo ahora el modelo está listo para ser usado. + demosSection.classList.remove('invisible'); +}); + + +var children = []; + +function predictWebcam() { + // Ahora vamos a empezar a clasificar un cuadro en el flujo de video. + model.detect(video).then(function (predictions) { + // Elimina cualquier resalto que hayamos hecho en el cuadro anterior. + for (let i = 0; i < children.length; i++) { + liveView.removeChild(children[i]); + } + children.splice(0); + + // Ahora vamos a recorrer las predicciones y dibujarlas en la vista en vivo si + // tienen una puntuación de confianza alta. + for (let n = 0; n < predictions.length; n++) { + // Si estamos más de un 66% seguras de que lo hemos clasificado bien, ¡dibújalo! + if (predictions[n].score > 0.66) { + const p = document.createElement('p'); + p.innerText = predictions[n].class + ' - with ' + + Math.round(parseFloat(predictions[n].score) * 100) + + '% confidence.'; + p.style = 'margin-left: ' + predictions[n].bbox[0] + 'px; margin-top: ' + + (predictions[n].bbox[1] - 10) + 'px; width: ' + + (predictions[n].bbox[2] - 10) + 'px; top: 0; left: 0;'; + + const highlighter = document.createElement('div'); + highlighter.setAttribute('class', 'highlighter'); + highlighter.style = 'left: ' + predictions[n].bbox[0] + 'px; top: ' + + predictions[n].bbox[1] + 'px; width: ' + + predictions[n].bbox[2] + 'px; height: ' + + predictions[n].bbox[3] + 'px;'; + + liveView.appendChild(highlighter); + liveView.appendChild(p); + children.push(highlighter); + children.push(p); + } + } + + // Llama a esta función de nuevo para seguir prediciendo cuando el navegador está listo. + window.requestAnimationFrame(predictWebcam); + }); +} \ No newline at end of file diff --git a/style.css b/style.css new file mode 100644 index 0000000..ab34c44 --- /dev/null +++ b/style.css @@ -0,0 +1,71 @@ +/** + * @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. + * ============================================================================= + */ + +/* Los archivos CSS añaden reglas de estilo al contenido */ + +body { + font-family: helvetica, arial, sans-serif; + margin: 2em; + color: #3D3D3D; +} + +h1 { + font-style: italic; + color: #FF6F00; +} + +video { + display: block; +} + +section { + opacity: 1; + transition: opacity 500ms ease-in-out; +} + +.removed { + display: none; +} + +.invisible { + opacity: 0.2; +} + +.camView { + position: relative; + float: left; + width: calc(100% - 20px); + margin: 10px; + cursor: pointer; +} + +.camView 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; +} \ No newline at end of file