Visión de IA#
Introducción#
El sensor de visión de IA del robot de codificación VEX AIM detecta y rastrea objetos, colores y AprilTags. Esto le permite analizar su entorno, seguir objetos y reaccionar según los datos visuales detectados. A continuación, se muestra una lista de todos los métodos y propiedades disponibles:
Acciones: Mostrar u ocultar la transmisión de la cámara AI Vision.
show_aivision – Displays the AI Vision feed on the robot’s screen.
hide_aivision – Hides the AI Vision feed from the screen.
tag_detection – Turns AprilTag detection on or off.
Getters – Detectan si el robot está sosteniendo un objeto.
get_data – Returns a tuple of detected objects based on a given signature.
has_sports_ball – Returns whether the robot has a sports ball.
has_any_barrel – Returns whether the robot has any type of barrel.
has_blue_barrel – Returns whether the robot has a blue barrel.
has_orange_barrel – Returns whether the robot has an orange barrel.
Properties – Object data returned from get_data.
exists – Whether the object exists in the current detection as a Boolean.
width – Width of the detected object in pixels.
height – Height of the detected object in pixels.
centerX – X position of the object’s center in pixels.
centerY – Y position of the object’s center in pixels.
bearing – Horizontal angle relative to the front of the robot in degrees.
rotation – Orientation of the object in degrees.
originX – X position of the object’s top-left corner in pixels.
originY – Y position of the object’s top-left corner in pixels.
id – Classification or tag ID of the object.
score – Confidence score for AI Classifications (1–100).
type – Returns the object’s type (AI, Tag, Color, or Code).
Constructores: definen firmas y códigos de color.
Create a Color Signature – Creates a new Color Signature based on RGB and hue/saturation ranges.
Create a Color Code – Combines multiple Color Signatures into a single Color Code.
Comportamiento#
show_aivision#
show_aivision
muestra la señal de datos en vivo del sensor de visión de IA en la pantalla del robot. Esta señal cubrirá cualquier otra imagen o texto en pantalla.
Note: The screen will not display any other images or text unless hide_aivision is used to hide the feed.
Uso:
robot.screen.show_aivision()
Parámetros |
Descripción |
---|---|
Este método no tiene parámetros. |
# Watch the AI Vision Sensor detect AI Classifications
# and AprilTags as you move the robot
robot.screen.show_aivision()
hide_aivision#
hide_aivision
elimina la transmisión de datos en vivo del sensor de visión de IA de la pantalla del robot.
Uso:
robot.screen.hide_aivision()
Parámetros |
Descripción |
---|---|
Este método no tiene parámetros. |
# View the AI Vision Sensor's feed for five seconds
robot.screen.show_aivision()
wait(5, SECONDS)
robot.screen.hide_aivision()
tag_detection#
tag_detection
habilita o deshabilita la detección de AprilTag, donde el estado es un valor booleano.
El sensor puede detectar los ID de AprilTag 0 a 36 de la familia Circle21h7.
Uso:
robot.vision.tag_detection(state)
Parámetros |
Descripción |
---|---|
|
|
robot.screen.set_font(PROP30)
# Cut off APrilTag detection after 5 seconds
while True:
if robot.timer.time(SECONDS) > 5:
robot.vision.tag_detection(False)
robot.screen.clear_screen()
robot.screen.set_cursor(3, 1)
apriltags = robot.vision.get_data(ALL_TAGS)
if apriltags:
robot.screen.print("AprilTag detected!")
else:
robot.screen.print("Nothing detected!")
wait(0.1, SECONDS)
Captadores#
get_data#
get_data
filtra los datos del marco del sensor de visión de IA para devolver una tupla. El sensor de visión de IA puede detectar firmas que incluyen objetos preentrenados, AprilTags o colores y códigos de color configurados.
Color Signatures and Color Codes must be configured first in the AI Vision Utility before they can be used with this method.
The tuple stores objects ordered from largest to smallest by width, starting at index 0. Each object’s properties can be accessed using its index. An empty tuple is returned if no matching objects are detected.
Uso:
robot.vision.get_data(signature, count)
Parámetros |
Descripción |
---|---|
|
¿De qué firma obtener los datos? Las firmas disponibles son:
|
|
Opcional. Establece el número máximo de objetos que se pueden devolver, de 1 a 24 (valor predeterminado: 8). |
Nota: Las AprilTags 5 a 37 se pueden obtener utilizando las AprilTags impresas de AIM Printables.
# Move forward if a sports ball is detected
while True:
ball = robot.vision.get_data(SPORTS_BALL)
if ball:
robot.move_for(10, 0)
wait(50, MSEC)
Firmas de color#
A color signature is a unique color that the AI Vision Sensor can recognize. These signatures allow the sensor to detect and track objects based on their color. Once a Color Signature is configured, the sensor can identify objects with that specific color in its field of view. Color signatures are used with get_data to process and detect colored objects in real-time.
# Display if any objects match the Red_Box signature
while True:
robot.screen.set_cursor(1, 1)
robot.screen.clear_row(1)
# Change to any configured Color Signature
ai_objects = robot.vision.get_data(Red_Box)
if ai_objects:
robot.screen.print("Color signature detected!")
Códigos de color#
Un código de color es un patrón estructurado compuesto por de 2 a 4 firmas de color dispuestas en un orden específico. Estos códigos permiten al sensor de visión de IA reconocer patrones de colores predefinidos. Los códigos de color son útiles para identificar objetos complejos o crear marcadores únicos para la navegación autónoma.
# Display if any objects match the BlueRed code
while True:
robot.screen.set_cursor(1, 1)
robot.screen.clear_row(1)
# Change to any configured Color Code
ai_objects = robot.vision.get_data(BlueRed)
if ai_objects:
robot.screen.print("Color code detected!")
has_sports_ball#
has_sports_ball
devuelve un valor booleano que indica si el robot tiene actualmente una pelota deportiva.
True
– El robot tiene un balón deportivo.False
– El robot no tiene pelota deportiva.
Uso:
robot.has_sports_ball()
Parámetros |
Descripción |
---|---|
Este método no tiene parámetros. |
# Kick when the robot has a sports ball
while True:
if robot.has_sports_ball():
robot.kicker.kick(MEDIUM)
wait(50, MSEC)
has_any_barrel#
has_any_barrel
devuelve un valor booleano que indica si el robot tiene actualmente algún tipo de barril.
True
– El robot tiene un barril.False
– El robot no tiene barril.
Uso:
robot.has_any_barrel()
Parámetros |
Descripción |
---|---|
Este método no tiene parámetros. |
# Push a barrel away when detected
while True:
if robot.has_any_barrel():
robot.kicker.place()
wait(50, MSEC)
has_blue_barrel#
has_blue_barrel
devuelve un valor booleano que indica si el robot tiene actualmente un barril azul.
True
– El robot tiene un barril azul.False
– El robot no tiene un barril azul.
Uso:
robot.has_blue_barrel()
Parámetros |
Descripción |
---|---|
Este método no tiene parámetros. |
# Push a blue barrel away when detected
while True:
if robot.has_blue_barrel():
robot.kicker.place()
wait(50, MSEC)
has_orange_barrel#
has_orange_barrel
devuelve un valor booleano que indica si el robot tiene actualmente un barril naranja.
True
– El robot tiene un barril naranja.False
– El robot no tiene un barril naranja.
Uso:
robot.has_orange_barrel()
Parámetros |
Descripción |
---|---|
Este método no tiene parámetros. |
# Push an orange barrel away when detected
while True:
if robot.has_orange_barrel():
robot.kicker.place()
wait(50, MSEC)
Propiedades#
There are twelve properties that are included with each object stored in a tuple after the robot.vision.get_data method is used.
Algunos valores de propiedad se basan en la posición del objeto detectado en la vista del sensor de visión de IA en el momento en que se usó robot.vision.get_data
. El sensor de visión de IA tiene una resolución de 240 x 320 píxeles.
.exists#
.exists
devuelve un valor booleano que indica si el índice existe en la tupla o no.
True
: el índice existe.False
: El índice no existe.
# Check if at least two objects are detected
while True:
robot.screen.clear_screen()
robot.screen.set_cursor(1, 1)
ai_objects = robot.vision.get_data(ALL_CARGO)
if ai_objects:
if ai_objects[1].exists:
robot.screen.print("More than 2")
else:
robot.screen.print("Less than 2")
wait(0.1, SECONDS)
.width#
.width
devuelve el ancho del objeto detectado en píxeles, que es un número entero entre 1 y 320.
# Move towards a Blue Barrel until its width is
# larger than 100 pixels
while True:
barrel = robot.vision.get_data(BLUE_BARREL)
if barrel:
if barrel[0].width < 100:
robot.move_at(0)
else:
robot.stop_all_movement()
wait(50, MSEC)
.height#
.height
devuelve la altura del objeto detectado en píxeles, que es un número entero entre 1 y 240.
# Move towards a Blue Barrel until its height is
# larger than 100 pixels
while True:
barrel = robot.vision.get_data(BLUE_BARREL)
if barrel:
if barrel[0].height < 100:
robot.move_at(0)
else:
robot.stop_all_movement()
wait(50, MSEC)
.centerX#
.centerX
devuelve la coordenada x del centro del objeto detectado en píxeles, que es un número entero entre 0 y 320.
# Turn slowly until a Blue Barrel is centered in
# front of the robot
robot.set_turn_velocity(30)
robot.turn(RIGHT)
while True:
barrel = robot.vision.get_data(BLUE_BARREL)
if barrel:
if 140 < barrel[0].centerX < 180:
robot.stop_all_movement()
wait(10,MSEC)
.centerY#
.centerY
devuelve la coordenada y del centro del objeto detectado en píxeles, que es un número entero entre 0 y 240.
# Move towards a Blue Barrel until its
# center y-coordinate is more than 140 pixels
while True:
barrel = robot.vision.get_data(BLUE_BARREL)
if barrel:
if barrel[0].centerY < 140:
robot.move_at(0)
else:
robot.stop_all_movement()
wait(50, MSEC)
.bearing#
.bearing
devuelve un valor flotante que representa la distancia de un objeto a la izquierda o a la derecha del centro de la vista del sensor de visión de IA, en grados. Un valor de 0 significa que está centrado, un valor positivo significa que el objeto está a la derecha y un valor negativo significa que está a la izquierda.
# Keep the blue barrel directly in front of the robot
robot.set_turn_velocity(40)
while True:
vision_data = robot.vision.get_data(BLUE_BARREL)
if vision_data:
if vision_data[0].bearing > 5:
robot.turn(RIGHT)
elif vision_data[0].bearing < -5:
robot.turn(LEFT)
else:
robot.stop_all_movement()
else:
robot.stop_all_movement()
wait(0.1, SECONDS)
.rotation#
.rotation
devuelve la orientación del objeto detectado en grados, que es un número entero entre 0 y 359.
# Slide left or right depending on how the
# AprilTag is rotated
while True:
apriltags = robot.vision.get_data(ALL_TAGS)
if apriltags:
if 50 < apriltags[0].rotation < 100 :
robot.move_at(90)
elif 270 < apriltags[0].rotation < 330 :
robot.move_at(270)
else:
robot.stop_all_movement()
else:
robot.stop_all_movement()
wait(50, MSEC)
.originX#
.originX
devuelve la coordenada x de la esquina superior izquierda del cuadro delimitador del objeto detectado en píxeles, que es un número entero entre 0 y 320.
# Display if an Orange Barrel is to the
# left or the right
while True:
robot.screen.clear_screen()
robot.screen.set_cursor(1,1)
orange_barrel = robot.vision.get_data(ORANGE_BARREL)
if orange_barrel:
if orange_barrel[0].originX < 160:
robot.screen.print("To the left!")
else:
robot.screen.print("To the right!")
wait(50, MSEC)
.originY#
.originY
devuelve la coordenada y de la esquina superior izquierda del cuadro delimitador del objeto detectado en píxeles, que es un número entero entre 0 y 240.
# Display if an Orange Barrel is close or far
# from the robot
while True:
robot.screen.clear_screen()
robot.screen.set_cursor(1, 1)
orange_barrel = robot.vision.get_data(ORANGE_BARREL)
if orange_barrel:
if orange_barrel[0].originY < 80:
robot.screen.print("Far")
else:
robot.screen.print("Close")
wait(50, MSEC)
.id#
.id
devuelve el ID de la clasificación de IA detectada o AprilTag como un entero.
Para un AprilTag, la propiedad .id
representa el número de identificación del AprilTag detectado en el rango de 0 a 36. Para una clasificación de IA, el id corresponde al id predefinido como se muestra a continuación.
Clasificación de IA |
identificación |
Firma |
---|---|---|
Pelota |
0 |
|
Barril azul |
1 |
|
Barril de naranja |
2 |
|
Robot AIM |
3 |
|
# Move forward when AprilTag 1 is detected
while True:
apriltags = robot.vision.get_data(ALL_TAGS)
if apriltags:
if apriltags[0].id == 1:
robot.move_at(0)
else:
robot.stop_all_movement()
wait(50, MSEC)
.score#
.score
devuelve la puntuación de confianza de la clasificación de IA detectada como un número entero entre 1 y 100.
# Look confident if an Orange Barrel is detected
while True:
barrel = robot.vision.get_data(ORANGE_BARREL)
if barrel:
if barrel[0].score > 95:
robot.screen.show_emoji(CONFIDENT)
else:
robot.screen.hide_emoji()
wait(50, MSEC)
.type#
.type
devuelve el tipo de objeto detectado. Devolverá uno de los siguientes:
Tipo de objeto |
Objetos incluidos |
---|---|
|
- Sports balls |
|
- AprilTags |
|
- Color signatures |
|
- Color codes |
# Display if an AprilTag or AI Classification
# is detected
while True:
robot.screen.clear_screen()
robot.screen.set_cursor(1, 1)
vision_data = robot.vision.get_data(ALL_VISION)
if vision_data:
if vision_data[0].type == AiVision.AI_OBJECT:
robot.screen.print("AI Object!")
elif vision_data[0].type == AiVision.TAG_OBJECT:
robot.screen.print("AprilTag!")
wait(0.1, SECONDS)
# Display a list of all detected objects
while True:
robot.screen.clear_screen()
robot.screen.set_cursor(1, 1)
vision_data = robot.vision.get_data(ALL_VISION)
if vision_data:
for obj in vision_data:
if obj.type == AiVision.AI_OBJECT:
robot.screen.print("- AI Object")
elif obj.type == AiVision.TAG_OBJECT:
robot.screen.print("- AprilTag")
robot.screen.next_row()
wait(0.1, SECONDS)
Constructores#
Creating a Color Signature#
Se crea una nueva firma de color mediante el constructor Colordesc
y luego se registra con el sensor de visión de IA mediante el método color_description
. Un objeto Colordesc
define una de hasta siete firmas de color detectables para el sensor, pero debe configurarse explícitamente mediante color_description
para que surta efecto.
Uso de Colordesc:
Colordesc(index, red, green, blue, hangle, hdsat)
Parámetro |
Descripción |
---|---|
|
Un número entero del 1 al 7 que representa el índice de la Firma de Color. Si dos Firmas de Color usan el mismo índice, la segunda prevalecerá sobre la primera. |
|
Un número entero de 0 a 255 para el componente rojo del color. |
|
Un número entero de 0 a 255 para el componente verde del color. |
|
Un número entero de 0 a 255 para el componente azul del color. |
|
Un flotante de 1 a 40 que representa el rango de tonos en grados. |
|
Un flotante de 0,10 a 1,00 que representa el rango de saturación. |
color_description Uso:
robot.vision.color_description(object)
Parámetro |
Descripción |
---|---|
|
El objeto |
# Detect a red object
red_box = Colordesc(1, 207, 19, 25, 10.00, 0.20)
robot.vision.color_description(red_box)
while True:
robot.screen.clear_screen()
robot.screen.set_cursor(1, 1)
red_boxes = robot.vision.get_data(red_box)
if red_boxes:
robot.screen.print("Red detected!")
else:
robot.screen.print("No red detected.")
wait(0.2, SECONDS)
Creating a Color Code#
Se crea un nuevo código de color mediante el constructor Codedesc
y luego se activa con el método code_description
. Un código de color agrupa de 2 a 4 objetos Colordesc
existentes en un único identificador que el sensor de visión de IA puede detectar como una secuencia. Sin embargo, debe configurarse explícitamente mediante code_description
para que surta efecto.
Uso de Codedesc:
Codedesc(index, c1, c2, c3, c4, c5)
Parámetro |
Descripción |
---|---|
|
El índice del código de color, de 1 a 8. Nota: Si crea dos objetos |
|
El primer objeto |
|
El segundo objeto |
|
Opcional. Un tercer objeto |
|
Opcional. Un cuarto objeto |
code_description Uso:
robot.vision.code_description(object)
Parámetro |
Descripción |
---|---|
|
Un objeto |
# Create Color Signatures
red_box = Colordesc(1, 207, 19, 25, 10.00, 0.20)
purple_box = Colordesc(2, 98, 18, 227, 10.00, 0.20)
robot.vision.color_description(red_box)
robot.vision.color_description(purple_box)
# Detect a red_purple Color Code
red_purple = Codedesc(1, red_box, purple_box)
robot.vision.code_description(red_purple)
while True:
robot.screen.clear_screen()
robot.screen.set_cursor(1, 1)
code_objects = robot.vision.get_data(red_purple)
if code_objects:
robot.screen.print("Code detected!")
else:
robot.screen.print("No code detected.")
wait(0.2, SECONDS)