AiVision#

El sensor de visión de IA debe estar conectado a su V5 Brain y configurado en VEXcode V5 antes de poder usarlo. Para obtener información sobre Introducción al sensor de visión de IA con VEX V5

Consulte estos artículos para obtener más información sobre el uso del sensor de visión IA.

Para obtener información más detallada sobre el uso del sensor de visión de IA con bloques en VEXcode V5, lea Codificación con el sensor de visión de IA en Python en VEXcode V5.

Inicializando la clase AiVision#

Un sensor de visión de IA se crea utilizando el siguiente constructor:

AiVision(port, colors, codes)

Este constructor utiliza tres parámetros:

Parámetro

Descripción

port

Un Puerto inteligente válido al que está conectado el sensor de visión de IA.

colors

Opcional. El nombre de uno o más objetos Colordesc.

codes

Opcional. El nombre de uno o más objetos Codedesc.

# Create a new Color Signature "red" with the Colordesc class.
red = Colordesc(1, 207, 19, 25, 10.00, 0.20)
# Create a new AI Vision Sensor "ai_vision" with the AiVision
# class, with the "red' Colordesc.
ai_vision = AiVision(Ports.PORT1, red)

This ai_vision AiVision object and red Colordesc object will be used in all subsequent examples throughout this API documentation when referring to AiVision class methods.

Métodos de clase#

take_snapshot()#

The take_snapshot(type, count) method takes the current snapshot visible to the AI Vision Sensor and detects the objects of a given signature, code, or signature id.

Parámetros

Descripción

tipo

Un objeto Colordesc, Codedesc, Tagdesc o AiObjdesc.

contar

Opcional. El número máximo de objetos a obtener. El valor predeterminado es 8.

Al tomar una instantánea, se creará una tupla con todos los objetos detectados que especificó. Por ejemplo, si desea detectar una firma de color “Azul” y el sensor de visión de IA detecta tres objetos azules diferentes, los datos de los tres se incluirán en la tupla.

Devuelve: Una tupla de objetos detectados o una tupla vacía si no se detecta nada.

Hay diez propiedades diferentes que se pueden llamar desde la tupla para obtener datos del objeto especificado.

  • id

  • centerX and centerY

  • originX and originY

  • width and height

  • angle

  • exists

  • score

To access an object’s property, use the name of the tuple, and then the object’s index. For example, if the tuple is stored in a variable named vision_objects you would call the width property as: vision_objects[0].width

identificación#

The id property is only available for AprilTags and AI Classifications.

For an AprilTag, the id property represents the detected AprilTag(s) ID number.

For AI Classifications, the id property represents the specific type of AI Classification detected. For more information on what IDs AI Classifications have, go to this article.

To call the id property, a tuple must be created first using the ai_vision.take_snapshot command.

Tras crear una tupla, se puede acceder a objetos específicos y sus propiedades mediante su índice. La tupla se ordena por área de objeto, de mayor a menor, con índices que empiezan en 0.

Nota: Las etiquetas AprilTags se ordenan por sus ID únicos en orden ascendente, no por tamaño. Por ejemplo, si se detectan las etiquetas AprilTags 1, 15 y 3:

  • AprilTag 1 tendrá índice 0.

  • AprilTag 3 tendrá índice 1.

  • AprilTag 15 tendrá índice 2.

To call this property, use the tuple followed by the index of the detected object to pull the property from. For example: vision_objects[0].id.

centroX y centroY#

The centerX and centerY properties report the center coordinates of the detected object in pixels.

To call these properties, a tuple must be created first using the ai_vision.take_snapshot command.

Tras crear una tupla, se puede acceder a objetos específicos y sus propiedades mediante su índice. La tupla se ordena por área de objeto, de mayor a menor, con índices que empiezan en 0.

To call this property, use the tuple followed by the index of the detected object to pull the property from. For example: vision_objects[0].centerX.

En este ejemplo, debido a que el centro de la vista del sensor de visión de IA es (160, 120), el robot girará a la derecha hasta que la coordenada centerX de un objeto detectado sea mayor a 150 píxeles, pero menor a 170 píxeles.

while True:
    # Get a snapshot of all Blue Color Signatures and store
    # it in vision_objects.
    vision_objects = ai_vision.take_snapshot(ai_vision_1__Blue)

    # Check to make sure an object was detected in the
    # snapshot before pulling data.
    if vision_objects[0].exists == True

        # Check if the object isn't in the center of the
        # AI Vision Sensor's view.
        if vision_objects[0].centerX > 150 and 170 > vision_objects[0].centerX:

            # Keep turning right until the object is in the
            # center of the view.
            drivetrain.turn(RIGHT)
        else:
            drivetrain.stop()
    wait(5, MSEC)

origenX y origenY#

The originX and originY properties report the coordinates, in pixels, of the top-left corner of the object’s bounding box.

To call these properties, a tuple must be created first using the ai_vision.take_snapshot command.

Tras crear una tupla, se puede acceder a objetos específicos y sus propiedades mediante su índice. La tupla se ordena por área de objeto, de mayor a menor, con índices que empiezan en 0.

To call a property, use the objects method followed by the index of the detected object to pull the property from. For example: vision_objects[0].originX.

En este ejemplo, se dibujará un rectángulo en la pantalla del Cerebro con las medidas exactas del cuadro delimitador del objeto especificado.

while True:
    # Get a snapshot of all Blue Color Signatures and store
    # it in vision_objects.
    vision_objects = ai_vision.take_snapshot(ai_vision_1__Blue)

    brain.screen.clear_screen()

    # Check to make sure an object was detected in the
    # snapshot before pulling data.
    if len(vision_objects) > 0:
        brain.screen.draw_rectangle(vision_objects[0].originX, vision_objects[0].originY, vision_objects[0].width, vision_objects[0].height)

    wait(5, MSEC)

ancho y alto#

The width and height properties report the width or height of the object in pixels.

To call these properties, a tuple must be created first using the ai_vision.take_snapshot command.

Tras crear una tupla, se puede acceder a objetos específicos y sus propiedades mediante su índice. La tupla se ordena por área de objeto, de mayor a menor, con índices que empiezan en 0.

To call a property, use the objects method followed by the index of the detected object to pull the property from. For example: vision_objects[0].width.

En este ejemplo, se utiliza el ancho del objeto para la navegación. El robot se acercará al objeto hasta que alcance un tamaño específico antes de detenerse.

while True:
    # Get a snapshot of all Blue Color Signatures and store
    # it in vision_objects.
    vision_objects = ai_vision.take_snapshot(ai_vision_1__Blue)

    # Check to make sure an object was detected in the
    # snapshot before pulling data.
    if vision_objects[0].exists == True

        # Check if the largest object is close to the
        # AI Vision Sensor by measuring its width.
        if vision_objects[0].width < 250:

            # Drive closer to the object until it's wider
            # than 250 pixels.
            drivetrain.drive(FORWARD)
        else:
            drivetrain.stop()

    wait(5, MSEC)

ángulo#

The angle property is only available for Color Codes and AprilTags.

Esta propiedad informa el ángulo del Código de color o de la Etiqueta de abril detectado.

To call the angle property, a tuple must be created first using the ai_vision.take_snapshot command.

Tras crear una tupla, se puede acceder a objetos específicos y sus propiedades mediante su índice. La tupla se ordena por área de objeto, de mayor a menor, con índices que empiezan en 0.

To call this property, use the tuple followed by the index of the detected object to pull the property from. For example: vision_objects[0].angle.

En este ejemplo, el ángulo de AprilTag se imprime en la pantalla del cerebro.

while True:
    # Get a snapshot of all Blue Color Signatures and store
    # it in vision_objects.
    vision_objects = ai_vision.take_snapshot(AiVision.ALL_TAGS)

    brain.screen.clear_screen()

    # Check to make sure an object was detected in the
    # snapshot before pulling data.
    if len(vision_objects) > 0:
        brain.screen.print(vision_objects[0].angle)

    wait(5, MSEC)

existe#

Esta propiedad devuelve un valor booleano que indica si el objeto especificado existe o no.

To call the exists property, a tuple must be created first using the ai_vision.take_snapshot command.

Tras crear una tupla, se puede acceder a objetos específicos y sus propiedades mediante su índice. La tupla se ordena por área de objeto, de mayor a menor, con índices que empiezan en 0.

To call this property, use the tuple followed by the index of the detected object to pull the property from. For example: vision_objects[0].exists.

En este ejemplo, se verifica si el objeto existe antes de intentar extraer datos de él para la navegación.

while True:
    # Get a snapshot of all Blue Color Signatures and store
    # it in vision_objects.
    vision_objects = ai_vision.take_snapshot(ai_vision_1__Blue)

    # Check to make sure an object was detected in the
    # snapshot before pulling data.
    if vision_objects[0].exists == True

        # Check if the largest object is close to the
        # AI Vision Sensor by measuring its width.
        if vision_objects[0].width < 250:

            # Drive closer to the object until it's wider
            # than 250 pixels.
            drivetrain.drive(FORWARD)
        else:
            drivetrain.stop()

    wait(5, MSEC)

puntaje#

The score property is only available for AI Classifications.

Esta propiedad devuelve la puntuación de confianza de la clasificación de IA especificada. La puntuación oscila entre el 0 % y el 100 %, lo que indica el nivel de certeza del sensor de visión de IA en su precisión de detección.

To call the exists property, a tuple must be created first using the ai_vision.take_snapshot command.

Tras crear una tupla, se puede acceder a objetos específicos y sus propiedades mediante su índice. La tupla se ordena por área de objeto, de mayor a menor, con índices que empiezan en 0.

To call this property, use the tuple followed by the index of the detected object to pull the property from. For example: vision_objects[0].score.

object_count()#

The object_count() method returns the amount of detected objects in the last use of the take_snapshot method.

Returns: An integer as the amount of detected objects in the last use of the take_snapshot method.

tag_detection()#

The tag_detection(enable) method enables or disables AprilTag detection.

Parámetros

Descripción

permitir

True to enable AprilTag detection. False to disable it.

Devoluciones: Ninguna.

color_detection()#

The color_detection(enable, merge) method enables or disables color and code object detection.

Parámetros

Descripción

permitir

True to enable color and color code detection. False to disable it.

unir

Opcional. Un valor booleano que habilita o deshabilita la fusión de detecciones de colores adyacentes.

Devoluciones: Ninguna.

model_detection(enable)#

The model_detection(enable) method enables or disables AI model object detection.

Parámetros

Descripción

permitir

True to enable AI model object detection. False to disable it.

Devoluciones: Ninguna.

start_awb()#

The start_awb() method runs auto white balance.

Devoluciones: Ninguna.

set()#

The set() method sets a new Color Signature or Color Code.

Devoluciones: Ninguna.

installed()#

The installed() method checks for device connection.

Returns: True if the AI Vision Sensor is connected. False if it is not.

timestamp()#

The timestamp() method requests the timestamp of the last received status packet from the AI Vision Sensor.

Devuelve: Marca de tiempo del último paquete de estado en milisegundos.