Ver categorías

Detección de objetos - detecta objetos en Scratch.

🎯 Detección de objetos - detecta objetos en Scratch #

La extensión Detección de objetos incorpora a Scratch un verdadero sistema de reconocimiento de objetos basado en inteligencia artificial.
Permite que tu proyecto identifique varios objetos mediante la imagen en directo de la cámara o el escenario de Scratch, los cuente, obtenga su posición y tamaño, y reaccione cuando aparezcan.
Como los modelos ya están entrenados, los estudiantes pueden comenzar a experimentar inmediatamente con la visión artificial, sin necesidad de entrenar un modelo ni realizar configuraciones externas.
Es lo suficientemente sencilla para principiantes y, a la vez, lo bastante potente para proyectos educativos de IA, STEM y juegos interactivos. 🤖

 


🌟 Descripción general #

  • Detecta varios objetos: Reconoce varios objetos compatibles en una misma imagen o fotograma de la cámara.
  • Cuenta lo que ve la IA: Obtén el número total de detecciones o cuenta únicamente un objeto específico.
  • Sigue la posición y el tamaño: Obtén las coordenadas X/Y del centro, el ancho y la altura de los objetos detectados en unidades del escenario de Scratch.
  • Filtra lo que importa Detecta todo lo que reconoce el modelo o crea tu propia lista de nombres de objetos para centrar la detección en ellos.
  • Guarda y ordena las detecciones: Guarda una captura de las detecciones seleccionadas y ordénalas según su nivel de confianza, posición o tamaño.
  • Activa eventos: Usa bloques de sombrero para reaccionar cuando aparezca un objeto o cambie el número de detecciones.
  • Elige el modelo adecuado: Cambia entre las opciones de detección Rápida, Equilibrada y Amplia según tu dispositivo, el nivel de detalle de la imagen y la variedad de objetos que necesites.
  • Elige la entrada: Detecta objetos mediante la imagen en directo de la cámara o directamente desde la imagen del escenario de Scratch.

✨ Características principales #

  • Detección de objetos con modelos preentrenados y sin necesidad de prompts; no requiere ninguna fase de entrenamiento.
  • Detecta varios objetos en una misma imagen y trabaja con cada detección de forma individual.
  • Obtén los nombres, las cantidades, el nivel de confianza, la posición, el ancho y la altura de los objetos.
  • Al crear proyectos más avanzados, elige entre las detecciones actuales en tiempo real y una captura guardada.
  • Crea una lista de detección personalizada para ignorar los objetos que no sean importantes para tu proyecto.
  • Guarda y ordena las detecciones de izquierda a derecha, de arriba abajo, de mayor a menor tamaño o de mayor a menor nivel de confianza; también puedes invertir cualquiera de estos órdenes.
  • Los bloques de sombrero facilitan la creación de juegos controlados mediante objetos y de escenas interactivas.
  • Los intervalos de detección ajustables ayudan a equilibrar la velocidad y el rendimiento del dispositivo.
  • Funciona completamente en el navegador – seguro y privado.

🚀 Cómo usar #

  1. Ve a: pishi.ai/play
  2. Abre la sección Extensiones.
  3. Selecciona la extensión «Detección de objetos».
  4. Permite el acceso a la cámara cuando se te solicite y verifica que aparezca la vista previa.
  5. Si lo prefieres, usa el escenario de Scratch como entrada para detectar objetos en su imagen, incluido cualquier vídeo de la cámara que se muestre allí. Para obtener el mejor rendimiento en tiempo real, utiliza la entrada de la cámara, ya que procesar el escenario puede ser más lento.
  6. La extensión comienza con el modelo de detección «Rápido». Puedes cambiar en cualquier momento entre «Rápido», «Equilibrado» y «Amplio» para ajustar el equilibrio entre velocidad, detalle y cobertura de objetos.
  7. Prueba el bloque reportero «lista de detecciones [actuales]» para ver los nombres de los objetos que reconoce la IA.
  8. Después, utiliza los bloques de conteo, posición, detecciones guardadas, filtrado y eventos para crear tu proyecto.

Consejos

  • Utiliza una iluminación clara y mantén el objeto lo bastante grande para que se vea fácilmente en el encuadre.
  • Comienza con un solo objeto compatible antes de crear un proyecto que dependa de varios objetos.
  • Cuando escribas el nombre de un objeto en otro bloque, utiliza exactamente la etiqueta devuelta por el bloque reportero «lista de detecciones [SOURCE]».
  • El vocabulario de objetos y las etiquetas de detección están en inglés; por lo tanto, utiliza las etiquetas en inglés al introducir nombres de objetos.
  • «Actuales» se refiere a los resultados más recientes de la detección en tiempo real. «Guardadas» se refiere a una captura creada con el bloque de guardar y ordenar.
  • Si aparece más de un objeto del mismo tipo, utiliza #1, #2, #3 y así sucesivamente para trabajar con cada detección por separado.
  • Si la detección funciona lentamente en un dispositivo, prueba el modelo «Rápido» o aumenta el intervalo de clasificación.

🧱 Bloques y funciones #

 

📊 Listas de detección, fuentes y cantidades #

Understanding SOURCE:

  • current – the latest live detections from the camera or stage.
  • saved – a snapshot stored by this block:
    save [OBJECT|text] from [SOURCE] detections, order by [ORDER_TYPE]

Using a saved snapshot is helpful when you want object order and positions to stay fixed while your project works with them.

 

Shared behavior: Reporter blocks that return a name, list, confidence, position, or size return an empty value when there is no matching detection, no saved snapshot is available, or the requested item number does not exist. Count reporters return 0, and Boolean blocks return false.

 

list of [SOURCE] detections

Reports the object labels in the selected detection source as comma-separated text.
Choose current to see what the AI recognizes right now, or saved to read the stored snapshot.
This is one of the best blocks for learning the exact object names the selected model uses in its detection results.

 

number of [SOURCE] detections

Reports the total number of objects in the selected source.
For example, it can count all live current detections or tell you how many objects are stored in saved detections.

 

all

Reports the special value all, which represents every detected object regardless of its label.
When you want a block to work with every detected object instead of one specific label, place it in an input of a block that asks for an object name (OBJECT).
You can also type all in English directly into the object-name input instead of using this reporter block.

 

save [OBJECT|text] from [SOURCE] detections, order by [ORDER_TYPE]

Takes matching detections from the selected source, sorts them, and stores the result as the new saved snapshot.
This is especially useful when you need a predictable order such as leftmost first, largest first, or highest confidence first.

By default, the current detection list is already ordered from highest to lowest confidence.

OBJECT: enter an object label such as person, comma-separated text such as person, car, or use all.

  • all: keeps all detections and saves them in the selected order. If you choose confidence high to low, the current detections are already in that order, so the block simply saves them as a snapshot.
  • An object name, such as person: filters the detections to that object and then sorts the matching results.
  • Multiple object names, such as person, car: combines detections matching any listed name and sorts them together.

SOURCE: choose current or saved.

  • current: uses the latest live detection results.
  • saved: uses the existing saved snapshot, allowing you to reorder it or filter it further.

ORDER_TYPE: order type can be:

  • confidence high to low o confidence low to high
  • left to right o right to left
  • top to bottom o bottom to top
  • large to small o small to large

After saving, choose saved in the SOURCE menu of other blocks to read the snapshot.
Saved detections stay unchanged until you save again, and switching the detection model clears the saved snapshot.

 

name of #[INDEX|text] [SOURCE] detection

Reports the label of one detection by its position in the selected source.
INDEX: use 1 for the first item, 2 for the second, and so on.
If the item does not exist, the block returns empty.
For saved detections, item 1, item 2, and so on follow the order that was selected when the detections were saved.

 

number of [OBJECT|text] in [SOURCE] detections

Reports how many detections in the selected source match an object name.
OBJECT: enter an exact object label, comma-separated text, or use all to count every object in the source.
When multiple names are provided, the block returns their combined detection count. For example, person, car counts every detected person and car.
Use this for counting games, classroom experiments, or logic such as “continue when two people are visible.”


📍 Posición, tamaño y confianza de detección #

confidence of [OBJECT|text] #[INDEX|text] in [SOURCE] detections

Reports the confidence of a selected detection on a scale from 0 to 1.
For example, 0.87 means the model gave that detection a confidence score of about 87%.

OBJECT: enter an exact object label, or use all to select items from the whole source.

INDEX: selects the first, second, third, and so on matching item.

SOURCE: choose current or saved.

 

x of [OBJECT|text] #[INDEX|text] in [SOURCE] detections

Reports the X position of the center of the selected detection box, mapped to Scratch stage coordinates.

Use it to move a sprite left or right with a real-world object.

Nota: A detection box is the rectangular area around a detected object that shows where the object is located in the image.

 

y of [OBJECT|text] #[INDEX|text] in [SOURCE] detections

Reports the Y position of the center of the selected detection box, mapped to Scratch stage coordinates.
Use it for vertical tracking, aiming, or object-controlled games.

 

width of [OBJECT|text] #[INDEX|text] in [SOURCE] detections

Reports the width of the selected detection box in Scratch stage units.
A larger value means the detected object occupies more horizontal space in the image.

 

height of [OBJECT|text] #[INDEX|text] in [SOURCE] detections

Reports the height of the selected detection box in Scratch stage units.

 

anything in [SOURCE] detections?

Returns true when the selected source contains at least one detection and false when it is empty.
With current, this checks the live scene. With saved, it checks the stored snapshot.

 

[OBJECT|text] #[INDEX|text] detected in [SOURCE] detections?

Checks whether a particular object and item number exists in the selected source.
For example, person #2 is true only when a second matching person detection exists.
You can also use all as the object value to test whether a particular item number exists in the whole source.


🎯 Modos de detección y listas personalizadas #

look for [MODE]

Controls which detected objects are included in the results used by the extension’s other blocks and detection events.

MODE:

  • all detections – keep every object recognized by the selected model.
  • my detection list – keep only object names that you have added to your custom detection list.

Importante: The my detection list is empty when the extension starts. You can switch to this mode at any time, but no detections will be reported until the list contains at least one object name.

 

my detection list

Reports your custom object list as comma-separated text.
The list can also store a history of newly detected object names without duplicates. For example, when the detection count changes, add the list of current detections to my detection list. Adding a name that is already in the list, even with different capitalization, does not add it again.

 

my detection list item #[INDEX|text]

Reports the object name at the selected position in your custom detection list.
INDEX: use 1 for the first item, 2 for the second, and so on.
If the item does not exist, the block returns empty.

 

number of items in my detection list

Reports how many unique object names are in your custom detection list.
This counts configured names, not objects currently visible to the camera.

 

add [OBJECT|text] to my detection list

Adds an object label to the custom list.
Use the exact label returned by the model.
Comma-separated text adds each label separately.
Adding the same name again does not create a duplicate entry.

 

remove [OBJECT|text] from my detection list

Removes the matching object name from your custom list.
Comma-separated text removes every matching label.

 

clear my detection list

Removes every name from the custom detection list.


⚡ Bloques de sombrero y reacciones #

when any object detected

Runs the attached script when the stable number of any detected object increases.
It can trigger when the first object appears, when a new object label appears, or when an additional instance of an already visible object is detected.

 

when [OBJECT|text] detected

Runs when the stable count of the named object increases.
For example, it can trigger when the first person appears and again if another person is newly detected.
Enter comma-separated text to run when the stable count of any listed object increases.
Using all here gives the same “when any object detected” behavior as the previous hat block.

 

when detections count changed

Runs when the total stable number of currently detected objects changes, either up or down.
This is useful for counting games and scenes that react when objects enter or leave the camera view.

 

Nota: detection hats wait for the same count to be seen in 2 consecutive frames before treating it as stable. This helps reduce one-frame flicker and accidental triggers.


🧠 Controles del modelo y de la confianza #

find using [MODEL_NAME] model

Switches the active object detection model.
The extension starts with the Fast model. Students can switch between models depending on whether their project needs faster detection, more image detail, or support for a wider range of object types.

Model Menu Input Size Classes Ideal para
fast size: 320 classes: 365 320×320 365 Lower processing load and smoother performance on less powerful devices
balanced size: 640 classes: 365 640×640 365 More image detail while using the same 365-class object vocabulary
wide size: 640 classes: 4585 640×640 4,585 A much wider object vocabulary when the 365-class options do not include what you need

↔ Desliza hacia la izquierda o hacia la derecha para ver la tabla completa en dispositivos móviles.

 

Consejo: Start with the default Fast model for responsive detection. Choose balanced for more image detail, or wide when you need many more object categories.

Importante: switching models clears saved detections. The current minimum confidence setting is kept when switching models.

 

establecer confianza mínima [CONFIDENCE|text]

Sets the minimum confidence required before a model result is reported as a detection.

The setting uses a scale from 0 to 1:

  • 0.35 – default.
  • 0.5-0.7 – stricter; can reduce weak or false detections.
  • 0.2-0.3 – more permissive; may help with difficult detections but can also increase mistakes.

This is a useful way to teach students that AI predictions are not simply “right” or “wrong” – each detection comes with a confidence score.

 

confianza mínima

Reports the current minimum confidence setting on the 0-1 scale.

Remember: both “minimum confidence” and “confidence of [OBJECT] #[INDEX] in [SOURCE] detections” use the same 0-1 scale.


⚙️ Controles de Clasificación #

  • clasificar [INTERVAL] - Elige con qué frecuencia se ejecuta la detección:
    • cada vez que se ejecuta este bloque
    • continuo, sin retraso
    • continuo, cada 50–2500 ms
  • activar clasificación [on_off] - Inicia o detiene la detección continua.
  • intervalo de clasificación - Devuelve el intervalo actual en milisegundos.
  • clasificación continua - Indica si la detección continua está “on” u “off”.
  • seleccionar imagen de entrada [camera/stage] - Elige cámara o escenario (stage).
  • imagen de entrada - Devuelve la fuente de entrada activa.

🎥 Controles de Video #

  • activar vídeo [off/on/on-flipped]
    • encendido: muestra la vista previa de la cámara en modo espejo (como una webcam típica).
    • encendido-invertido: muestra la vista previa sin espejo — las direcciones aparecen como en el mundo real.
    • apagado: apaga la vista previa de la cámara. En modo stage, la detección continúa funcionando.
  • fijar transparencia de vídeo a [TRANSPARENCY|text] — Ajusta qué tan visible es la vista previa
    • 0: completamente visible
    • 100: completamente transparente (invisible pero activa)
    Usa un valor de 0–100 para ajustar la opacidad y ayudar a que los sprites se vean claramente sobre la cámara.
  • seleccionar cámara [CAMERA] — permite elegir entre las cámaras disponibles en tu dispositivo. El menú desplegable muestra todas las cámaras detectadas y la extensión cambia automáticamente a la que selecciones.
  • mostrar cuadros de detección [encendido/apagado]
    Activa o desactiva la visualización de los cuadros de detección. Cuando está activada, aparecen cuadros alrededor de cada objeto detectado para que puedas ver qué objetos está siguiendo el modelo. Esto es útil para probar la cámara, comprobar qué tan bien funciona el modelo y depurar un proyecto en tiempo real.

Detection boxes are enabled by default for this extension. Use the detection-box control when you want to show or hide the visual boxes around recognized objects.


🎓 Usos educativos #

  • Introduce Computer Vision: Students can see how an AI model turns images into object labels and locations.
  • Teach Confidence and Uncertainty: Compare predictions at different confidence thresholds and discuss why AI sometimes makes mistakes.
  • Explore Coordinates: Connect detected X/Y positions to sprite movement and Scratch’s coordinate system.
  • Explore Size: Use width and height to see how large an object appears in the image.
  • Practice Lists and Indexing: Work with the first, second, or third matching object and compare multiple detections.
  • Practice Sorting: Save detections and order them by position, size, or confidence.
  • Teach Events: Use hat blocks to show how software can react to changes in the environment.
  • Discuss AI Limitations: Compare what students see with what the model recognizes and investigate false positives, missed objects, lighting, angle, and object size.

🎮 Proyectos de ejemplo #

  • Object Greeter: Make a sprite say hello when a chosen supported object appears.
  • Object Counter: Show the number of visible objects and trigger a celebration when the count reaches a target.
  • Follow the Target: Use the X/Y center of a detected object to move a sprite toward it.
  • Left or Right? Save matching detections from left to right and use item 1 to find the leftmost object.
  • Biggest Object Challenge: Save detections from large to small and make Scratch react to the largest one.
  • AI Confidence Lab: Display confidence values and test how lighting, distance, angle, and background affect predictions.
  • Classroom Object Hunt: Give students a list of supported objects and score a point when the AI finds each one.
  • What’s in Frame? Display the “list of [SOURCE] detections” reporter block so students can observe how the model describes a changing scene.

🧩 Pruébalo tú mismo: pishi.ai/play

 


🔧 Consejos y solución de problemas #

  • ¿No hay cámara?
    • Asegúrate de que tu cámara esté conectada y que el navegador tenga permiso para usarla.
    • Si la cámara está bloqueada, actívala en la configuración de permisos del sitio del navegador y vuelve a cargar la página.
    • Al cargar la extensión, si no se detecta ninguna cámara, la imagen de entrada cambia automáticamente al escenario de Scratch, donde se muestran los fondos y los sprites, para que puedas seguir utilizando y probando las funciones de la extensión.
  • ¿No hay detección?
    clasificación continua: Usa este bloque informador para comprobar si la clasificación está activa.
    • Si está activa, mejora la iluminación y mira directamente a la cámara.
    activar clasificación [encendido]: Usa este bloque si la clasificación no está activa. Después vuelve a comprobar el estado de clasificación con el reportero anterior.
    • En el modo de entrada de cámara, cuando la cámara se apaga, la clasificación también se detiene. Debes volver a activar el vídeo o cambiar la entrada al escenario.
    • En el modo de entrada de escenario, el sistema clasifica todo lo que sea visible en el escenario: fondos, sprites o imágenes. Puedes apagar completamente el vídeo y aun así procesar imágenes del escenario.
    El modo escenario es más lento que la entrada por cámara, así que reduce tu intervalo de clasificación (por ejemplo, 100–250 ms) para obtener resultados más fluidos usando este bloque: clasificar [INTERVAL]
    • En el modo escenario, los puntos de referencia de “izquierda” y “derecha” están intercambiados porque la imagen del escenario no está reflejada. El sistema de coordenadas representa una vista real (sin espejo).
    • La clasificación también puede reiniciarse automáticamente cuando usas bloques como:
    activar vídeo [encendido] / clasificar [INTERVAL] / seleccionar cámara [CAMERA] / seleccionar imagen de entrada [camera/stage].
  • ¿Vista invertida?
    activar vídeo [encendido-invertido]: Usa esto para mostrar la cámara sin efecto espejo. “on” muestra la imagen reflejada como una selfie. “on-flipped” muestra la orientación real izquierda/derecha.
  • ¿Va lento o tiene retraso?
    Usa intervalos de clasificación entre 100–250 ms o cierra otras pestañas del navegador para reducir la carga de procesamiento.
  • ¿Advertencia de WebGL2?
    Prueba con Firefox o con un dispositivo más nuevo que sea compatible con aceleración gráfica WebGL2.
  • ¿Analizar el escenario en lugar de la cámara?
    seleccionar imagen de entrada [stage]: Usa esto para analizar la imagen del escenario de Scratch en lugar de una cámara en vivo. El escenario de Scratch puede incluir la imagen de la cámara, así como cualquier sprite y fondo que estén visibles en ese momento en el escenario.
    Nota: Procesar el escenario de Scratch puede ser más lento que usar la cámara directamente.

🎯 Consejos específicos para la detección de objetos #

  • No objects detected? Make sure classification is running, improve the lighting, move the object closer, and check that the selected model supports that object label.
  • The object has the wrong name? Each detection model uses its own learned object vocabulary. Check the “list of [current] detections” block to see the exact label it returns.
  • Too many false detections? Increase minimum confidence gradually, for example from 0.35 to 0.5.
  • A real object is often missed? Try better lighting, a clearer angle, the Balanced model, or a slightly lower confidence threshold.
  • Need an object that Fast or Balanced does not recognize? Try the Wide model, which uses a much larger class vocabulary.
  • Only interested in a few objects? Add those exact labels to my detection list, then switch “look for [MODE]” to my detection list.
  • My detection list mode suddenly detects nothing? Check that my detection list is not empty and that its names match the model labels exactly.
  • Item 2 or item 3 returns empty? That item number only works when enough matching detections currently exist.
  • Saved positions seem old? Saved detections are intentionally a snapshot. Run “save [OBJECT] from [SOURCE] detections, order by [ORDER_TYPE]” again, usually with current as the source, to refresh them.
  • Project is slow? Use the Fast model, increase the classification interval, close other heavy browser tabs, or reduce how often your Scratch scripts read detection data.
  • Camera is not available? Switch the input to stage and test with a backdrop, sprite, or imported image.

🔒 Privacidad y seguridad #

  • Todo se ejecuta localmente en tu navegador.
  • Ninguna imagen o vídeo se sube a ningún servidor.
  • Los archivos del modelo se cargan directamente desde Pishi.ai cuando se inicia la extensión, por lo que no se utilizan servidores de modelos de terceros.
  • Siempre pide permiso a un profesor o padre antes de usar la cámara.
  • Puedes usar este bloque de forma segura en cualquier momento activar vídeo [apagado].

🧪 Información técnica #

  • Model Type: Pre-trained ONNX object detection models.
  • Framework: onnxruntime-web.
  • Browser Execution: Desktop browsers prefer WebGPU when supported, with WebAssembly (WASM) fallback; Android uses WASM.
  • Model Options: Fast (320×320, 365 classes), Balanced (640×640, 365 classes), and Wide (640×640, 4,585 classes).
  • Starting Model: Fast (320×320) on every supported device.
  • Default Minimum Confidence: 0.35.
  • Detección Multiple objects can be reported from the same frame.
  • Confidence Reporter: Returns a value from 0-1.
  • Coordenadas: Detection-box centers are mapped to Scratch stage coordinates; width and height are reported in stage units.
  • Sources: Reporter blocks can read either current live detections or saved snapshot detections.
  • Filtering: Detection mode can keep all detections or only labels from the user’s custom detection list.
  • Saved Detections: A snapshot can be filtered and ordered by confidence, horizontal position, vertical position, or size.
  • Hat Stability: Detection count changes must remain the same for 2 consecutive frames before object-detection hats are treated as stable.
  • Detection Boxes: Visual detection boxes are enabled by default and can be controlled from the extension.
  • Entradas: Live camera or Scratch stage image.
  • Processing: Detection runs locally in the browser after the required model files are loaded.

🔗 Extensiones relacionadas #

  • 🖐️ Pose de la mano – detect hand landmarks and gestures.
  • 🕺 PoseNet – track full-body pose and movement.
  • 😎 Malla facial – detect facial landmarks and expressions.
  • 🖼️ Entrenador de Imágenes – train your own custom image classifier directly in Scratch.
  • 🏫 Máquina de enseñanza de Google – import pre-trained custom classification models.

🖼️ Detección de objetos frente a Entrenador de imágenes #

Característica Detección de objetos Entrenador de Imágenes
Training Uses pre-trained models – no training required Students train their own labels with examples
What it answers “What objects are here, how many, and where are they?” “Which label best matches this whole image?”
Multiple objects at once Not as separate located objects
Position and size Yes – X, Y, width, and height No object bounding-box position
Custom object categories Limited to labels available in the selected pre-trained detection model Yes – students create their own labels
Best classroom use Computer vision, object tracking, counting, coordinates, and event-driven projects Teaching machine learning, training data, examples, and custom visual commands

↔ Desliza hacia la izquierda o hacia la derecha para ver la tabla completa en dispositivos móviles.

 

💡 ¿Por qué elegir Detección de objetos? #

Choose Object Detection when your project needs to find real objects and know where they are.
It is especially useful when students want immediate results without training a model first.

  • Recognize several objects in the same scene.
  • Count objects and compare their positions or sizes.
  • Build projects that react to changes in the real world.
  • Explore confidence, filtering, sorting, and computer vision in a Scratch-friendly way.

💡 ¿Cuándo deberías usar Entrenador de imágenes en su lugar? #

Use Image Trainer when you need categories that are specific to your own project – for example, your own hand gestures, classroom cards, custom commands, or objects that a pre-trained detector does not know.
Image Trainer lets students create the labels themselves and learn directly from their own examples.

En resumen:
Use Object Detection to find and locate objects the AI already knows.
Use Image Trainer when you want to teach the AI your own visual categories.


📚 Más información #


Scroll al inicio