Vision#

The Vision and AI Vision Sensors enable robots to detect and track visual information in their environment. By identifying objects, colors, and patterns, these sensors allow robots to analyze their surroundings and respond to what they see.

Below is a list of all methods:

AI Vision Sensor

  • Getters

    • takeSnapshot – Captura datos para una firma de color o un código de color específico.

    • objectCount – Devuelve la cantidad de objetos detectados como un entero.

    • largestObject – Selecciona inmediatamente el objeto más grande de la instantánea.

  • Properties – Object data returned from takeSnapshot.

    • .exists – Si el objeto existe en la detección actual como un valor booleano.

    • .width – Ancho del objeto detectado en píxeles.

    • .height – Altura del objeto detectado en píxeles.

    • .centerX – Posición X del centro del objeto en píxeles.

    • .centerY – Posición Y del centro del objeto en píxeles.

    • .angle – Orientación del código de color en grados.

    • .originX – Posición X de la esquina superior izquierda del objeto en píxeles.

    • .originY – Posición Y de la esquina superior izquierda del objeto en píxeles.

    • .id – Classification or tag ID of the object.

    • .score – Confidence score for AI Classifications (1–100).

Vision Sensor

  • Getters

    • takeSnapshot – Captures data for a specific Color Signature or Color Code.

    • largestObject – Immediately select the largest object from the snapshot.

    • objectCount – Returns the number of detected objects as an integer.

    • objects – Returns an array containing the properties of detected objects.

    • installed – Whether the Vision Sensor is connected to the IQ (2nd Gen) Brain.

  • Propiedades: datos del objeto devueltos desde takeSnapshot.

    • .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.

    • .angle – Orientation of the Color Code 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.

Constructors – Manually initialize and configure the sensors.

AI Vision Sensor#

Tomar instantánea#

takeSnapshot captures an image from the AI Vision Sensor, processes it based on the signature, and updates the objects array. This method can also limit the amount of objects captured in the snapshot.

Las Firmas de color y los Códigos de color deben configurarse primero en Vision Utility antes de poder usarse con este método.

La matriz objects almacena objetos ordenados del más grande al más pequeño por ancho, comenzando en el índice 0. Se puede acceder a las propiedades de cada objeto usando su índice. objects es una matriz vacía si no se detectan objetos coincidentes.

Default Usage:
AIVision1.takeSnapshot(signature)

Overloads:
AIVision1.takeSnapshot(signature, count)

Parámetros

Descripción

firma

What signature to get data of.

  • Color Signatures or Color Codes – The name of the AI Vision Sensor, two underscores, and then the Color Signature’s or Color Code’s name.For example: AIVision1__redBox.
  • aivision::ALL_AIOBJS – Cubes, rings, and balls.
  • aivision::ALL_TAGS – All AprilTags.

contar

Optional. Sets the maximum number of objects that can be returned from 1 to 24 (default: 8).

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Move forward if an object is detected
  while (true) {
    AIVision1.takeSnapshot(aivision::ALL_AIOBJS);
    if (AIVision1.objects[0].exists) {
      Drivetrain.driveFor(forward, 50, mm);
    }
    wait(50, msec);
  }
}

Firmas de color#

A Color Signature is a unique color that the AI Vision Sensor can recognize. These signatures allow the AI Vision 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 take_snapshot to process and detect colored objects in real-time.

In order to use a configured Color Signature in a project, its name must be the name of the sensor, two underscores, and then the Color Signature’s name. For example: AIVision1__redBox.

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();

  while (true) {
    Brain.Screen.setCursor(1, 1);
    Brain.Screen.clearLine(1);
    // Change to any configured Color Signature
    AIVision1.takeSnapshot(AIVision1__redBox);
    if (AIVision1.objects[0].exists) {
      Brain.Screen.print("Detected!");
    }
    wait(50, msec);
  }
}

Códigos de color#

Un código de color es un patrón estructurado compuesto por firmas de color dispuestas en un orden específico. Estos códigos permiten al sensor de visión reconocer patrones de color predefinidos. Los códigos de color son útiles para identificar objetos complejos o crear marcadores únicos para la navegación autónoma.

To use a configured Color Code in a project, its name must be passed as a string in the format: the Vision Sensor’s name, followed by two underscores, and then the Color Code’s name. For example: AIVision1__redBlue.

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();

  while (true) {
    Brain.Screen.setCursor(1, 1);
    Brain.Screen.clearLine(1);
    // Change to any configured Color Code
    AIVision1.takeSnapshot(AIVision1__redBlue);
    if (AIVision1.objects[0].exists) {
      Brain.Screen.print("Detected!");
    }
    wait(50, msec);
  }
}

objeto más grande#

largestObject recupera el objeto más grande detectado de la matriz objects.

Este método se puede utilizar para obtener siempre el objeto más grande de objetos sin especificar un índice.

Default Usage:
AIVision1.largestObject

Parámetros

Descripción

Este método no tiene parámetros.

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Display the closest AprilTag's ID
  while (true) {
    Brain.Screen.setCursor(1, 1);
    Brain.Screen.clearLine(1);
    AIVision1.takeSnapshot(aivision::ALL_TAGS);
    if (AIVision1.objects[0].exists) {
      Brain.Screen.print("%d", AIVision1.largestObject.id);
    }
    wait(50, msec);
  }
}

objectCount#

objectCount devuelve el número de elementos dentro de la matriz objects como un entero.

Default Usage:
AIVision1.objectCount

Parámetros

Descripción

Este método no tiene parámetros.

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Display the number of detected objects
  while (true) {
    Brain.Screen.setCursor(1, 1);
    Brain.Screen.clearLine(1);
    AIVision1.takeSnapshot(aivision::ALL_AIOBJS);
    if (AIVision1.objects[0].exists) {
      Brain.Screen.print("%d", AIVision1.objectCount);
    }
    wait(50, msec);
  }
}

instalado#

installed returns an integer indicating whether the AI Vision Sensor is currently connected to the IQ (2nd Gen) Brain.

  • 1 – The AI Vision Sensor is connected to the IQ (2nd Gen) Brain.

  • 0 – The AI Vision Sensor is not connected to the IQ (2nd Gen) Brain.

Parámetros

Descripción

Este método no tiene parámetros.

// Display a message if the Vision Sensor is detected
if (AIVision1.installed()){
  Brain.Screen.print("Installed!");
}

objetos#

objects devuelve una matriz de propiedades de objetos detectados. Use la matriz para acceder a valores específicos de propiedad de objetos individuales.

Default Usage:
AIVision1.objects

Propiedades#

There are ten properties that are included with each object stored in the objects array after takeSnapshot is used.

Some property values are based off of the detected object’s position in the Vision Sensor’s view at the time that takeSnapshot was used. The AI Vision Sensor has a resolution of 320 by 240 pixels.

.existe#

.exists devuelve un entero que indica si el índice existe en la matriz objects o no.

  • 1: El índice existe.

  • 0: El índice no existe.

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Move forward if an object is detected
  while (true) {
    AIVision1.takeSnapshot(aivision::ALL_AIOBJS);
    if (AIVision1.objects[0].exists) {
      Drivetrain.driveFor(forward, 50, mm);
    }
    wait(50, msec);
  }
}

.ancho#

.width returns the width of the detected object in pixels, which is an integer between 1 and 320.

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Approach an object until it's at least 100 pixels wide
  while (true) {
    AIVision1.takeSnapshot(aivision::ALL_AIOBJS);

    if (AIVision1.objects[0].exists) {
      if (AIVision1.objects[0].width < 100) {
        Drivetrain.drive(forward);
      } else {
        Drivetrain.stop();
      }
    } else {
      Drivetrain.stop();
    }
    wait(50, msec);
  }
}

.altura#

.height returns the height of the detected object in pixels, which is an integer between 1 and 240.

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Approach an object until it's at least 90 pixels tall
  while (true) {
    AIVision1.takeSnapshot(aivision::ALL_AIOBJS);

    if (AIVision1.objects[0].exists) {
      if (AIVision1.objects[0].height < 90) {
        Drivetrain.drive(forward);
      } else {
        Drivetrain.stop();
      }
    } else {
      Drivetrain.stop();
    }
    wait(50, msec);
  }
}

.centroX#

.centerX returns the x-coordinate of the detected object’s center in pixels, which is an integer between 0 and 320.

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Turn until an object is directly in front of the sensor
  Drivetrain.setTurnVelocity(10, percent);
  Drivetrain.turn(right);
  while (true) {
    AIVision1.takeSnapshot(aivision::ALL_AIOBJS);

    if (AIVision1.objects[0].exists) {
      if (AIVision1.objects[0].centerX > 140 && AIVision1.objects[0].centerX < 180) {
        Drivetrain.stop();
      }
    }

    wait(10, msec);
  }
}

.centerY#

.centerY returns the y-coordinate of the detected object’s center in pixels, which is an integer between 0 and 240.

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Approach an object until it's at least 90 pixels tall
  while (true) {
    AIVision1.takeSnapshot(aivision::ALL_AIOBJS);

    if (AIVision1.objects[0].exists) {
      if (AIVision1.objects[0].centerY < 150) {
        Drivetrain.drive(forward);
      } else {
        Drivetrain.stop();
      }
    } else {
      Drivetrain.stop();
    }
    wait(50, msec);
  }
}

.ángulo#

.angle returns the orientation of the detected Color Code or AprilTag in degrees, which is a double between 0 and 360.

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Turn left or right depending on how a configured
  // Color Code is rotated
  while (true) {
    AIVision1.takeSnapshot(AIVision1__redBlue);
    if (AIVision1.objects[0].exists) {
      if (AIVision1.objects[0].angle > 50 && AIVision1.objects[0].angle < 100) {
        Drivetrain.turn(right);
      }
      else if (AIVision1.objects[0].angle > 270 && AIVision1.objects[0].angle < 330) {
        Drivetrain.turn(left);
      }
      else {
        Drivetrain.stop();
      }
    } else {
      Drivetrain.stop();
    }
    wait(50, msec);
  }
}

.origenX#

.originX returns the x-coordinate of the top-left corner of the detected object’s bounding box in pixels, which is an integer between 0 and 320.

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Display if an object is to the left or the right
  while (true) {
    Brain.Screen.clearScreen();
    Brain.Screen.setCursor(1, 1);
    AIVision1.takeSnapshot(aivision::ALL_AIOBJS);
    if (AIVision1.objects[0].exists) {
      if (AIVision1.objects[0].originX < 120) {
        Brain.Screen.print("To the left!");
      } else {
        Brain.Screen.print("To the right!");
      }
    } else {
      Brain.Screen.print("No objects");
    }
    wait(100, msec);
  }
}

.origenY#

.originY returns the y-coordinate of the top-left corner of the detected object’s bounding box in pixels, which is an integer between 0 and 240.

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Display if an object is close or far
  while (true) {
    Brain.Screen.clearScreen();
    Brain.Screen.setCursor(1, 1);
    AIVision1.takeSnapshot(aivision::ALL_AIOBJS);
    if (AIVision1.objects[0].exists) {
      Brain.Screen.print(AIVision1.objects[0].originY);
      Brain.Screen.newLine();
      if (AIVision1.objects[0].originY < 110) {
        Brain.Screen.print("Close");
      } else {
        Brain.Screen.print("Far");
      }
    }
    wait(100, msec);
  }
}

.id#

.id returns the ID of the detected AI Classification or AprilTag as an integer.

AI Classification

ID

Blue Ball

0

Green Ball

1

Red Ball

2

Blue Ring

3

Green Ring

4

Red Ring

5

Blue Cube

6

Green Cube

7

Red Cube

8

For an AprilTag, the .id property represents the detected AprilTag’s ID number in the range of 0 to 36. For an AI Classification, the id corresponds to the predefined id as shown below.

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Move forward when AprilTag 1 is detected
  while (true) {
    AIVision1.takeSnapshot(aivision::ALL_APRILTAGS);
    if (AIVision1.objects[0].exists) {
      if (AIVision1.objects[0].id == 1) {
        Drivetrain.drive(forward);
      }
    } else {
      Drivetrain.stop();
    }
    wait(50, msec);
  }
}

.score#

.score returns the confidence score of the detected AI Classification as an integer between 1 and 100.

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Display if a score is confident
  while (true) {
    AIVision1.takeSnapshot(aivision::ALL_AIOBJS);

    if (AIVision1.objects[0].exists) {
      if (AIVision1.objects[0].score > 95) {
        Brain.Screen.print("Confident");
      } else {
        Brain.Screen.print("Not confident");
      }
    }

    wait(50, msec);
  }
}

Sensor de visión#

Tomar instantánea#

takeSnapshot captures an image from the Vision Sensor, processes it based on the signature, and updates the objects array. This method can also limit the amount of objects captured in the snapshot.

Las Firmas de color y los Códigos de color deben configurarse primero en Vision Utility antes de poder usarse con este método.

La matriz objects almacena objetos ordenados del más grande al más pequeño por ancho, comenzando en el índice 0. Se puede acceder a las propiedades de cada objeto usando su índice. objects es una matriz vacía si no se detectan objetos coincidentes.

Uso predeterminado:
Vision1.takeSnapshot(signature)

Parámetro

Descripción

firma

What signature to get data of.

  • Color Signatures or Color Codes – The name of the AI Vision Sensor, two underscores, and then the Color Signature’s or Color Code’s name.For example: AIVision1__redBox.
  • aivision::ALL_AIOBJS – Cubes, rings, and balls.
  • aivision::ALL_TAGS – All AprilTags.

contar

Optional. Sets the maximum number of objects that can be returned from 1 to 24 (default: 8).

while (true) {
  // Take a snapshot to check for detected objects.
  Vision1.takeSnapshot(Vision1__BLUEBOX);

  // Clear the screen/reset so that we can display
  // new information.
  Brain.Screen.clearScreen();
  Brain.Screen.setCursor(1, 1);

  // If objects were found, print the location.
  if (Vision1.objects[0].exists) {
    Brain.Screen.print("Center X: %d", Vision1.largestObject.centerX);
  } 
  else {
    Brain.Screen.print("no object");
  }

  wait(0.5, seconds);
}

Sobrecarga

  • Vision1.takeSnapshot(firma, recuento)

Parámetro de sobrecarga

Descripción

contar

La cantidad de objetos a devolver como uint32_t donde se incluirán los objetos más grandes.

Ejemplos de sobrecarga

// Display a location if a blue box is detected
while (true) {
  // Take a snapshot of only one object
  Vision1.takeSnapshot(Vision1__BLUEBOX, 1);

  // Clear the screen/reset so that we can display
  // new information.
  Brain.Screen.clearScreen();
  Brain.Screen.setCursor(1, 1);

  // If object was found, print the location.
  if (Vision1.objects[0].exists) {
    Brain.Screen.print("Center X: %d", Vision1.largestObject.centerX);
  } 
  else {
    Brain.Screen.print("no object");
  }

  wait(0.5, seconds);
}

Firmas de color#

Una firma de color es un color único que el sensor de visión puede reconocer. Estas firmas permiten al sensor detectar y rastrear objetos según su color. Una vez configurada una firma de color, el sensor puede identificar objetos con ese color específico en su campo de visión. Las firmas de color se utilizan con take_snapshot para procesar y detectar objetos de color en tiempo real.

Para usar una Firma de Color configurada en un proyecto, su nombre debe pasarse como una cadena con el formato: el nombre del sensor de visión, seguido de dos guiones bajos y, a continuación, el nombre de la Firma de Color. Por ejemplo: vision_1__REDBOX.

//Display if any objects match the REDBOX signature
while (true) {
  // Take a snapshot to check for detected objects.
  Brain.Screen.setCursor(1, 1);
  Brain.Screen.clearLine(1);
  // Change to any configured Color Signature
  Vision1.takeSnapshot(Vision1__REDBOX);
  if (Vision1.objects[0].exists){
    Brain.Screen.print("Color signature detected!");
  }
}

Códigos de color#

Un código de color es un patrón estructurado compuesto por firmas de color dispuestas en un orden específico. Estos códigos permiten al sensor de visión reconocer patrones de color predefinidos. Los códigos de color son útiles para identificar objetos complejos o crear marcadores únicos para la navegación autónoma.

Para usar un código de color configurado en un proyecto, su nombre debe pasarse como una cadena con el formato: el nombre del sensor de visión, seguido de dos guiones bajos y, a continuación, el nombre del código de color. Por ejemplo: vision_1__BOXCODE.

// Display if any objects match the BOXCODE code
while (true) {
  // Take a snapshot to check for detected objects.
  Brain.Screen.setCursor(1, 1);
  Brain.Screen.clearLine(1);
  // Change to any configured Color Code
  Vision1.takeSnapshot(Vision1__BOXCODE);
  if (Vision1.objects[0].exists){
    Brain.Screen.print("Color Code Detected!");
    wait(0.1, seconds);
  }
}

objeto más grande#

largestObject recupera el objeto más grande detectado de la matriz objects.

Este método se puede utilizar para obtener siempre el objeto más grande de objetos sin especificar un índice.

Uso predeterminado:
Vision1.largestObject

while (true){
  // Take a snapshot to check for detected objects.
  Vision1.takeSnapshot(Vision1__BLUEBOX);
  // Clear the screen/reset so that we can display
  // new information.
  Brain.Screen.clearScreen();
  Brain.Screen.setCursor(1, 1);
  // If objects were found, print the location 
  // of largest.
  if (Vision1.objects[0].exists) {
    Brain.Screen.print("Center X: %d", Vision1.largestObject.centerX);
  } 
  else {
    Brain.Screen.print("no object");
  }
  wait(0.5, seconds);
}

objectCount#

objectCount devuelve el número de elementos dentro de la matriz objects como un entero.

Uso predeterminado:
Vision1.objectCount

while (true) {
  // Take a snapshot to check for detected objects.
  Vision1.takeSnapshot(Vision1__BLUEBOX);

  // Clear the screen/reset so that we can display
  // new information.
  Brain.Screen.clearScreen();
  Brain.Screen.setCursor(1, 1);

  // Print how many objects were detected.
  Brain.Screen.print("object count: %d", Vision1.objectCount);

  wait(0.5, seconds);
}

instalado#

installed devuelve un entero que indica si el sensor de visión está conectado actualmente al cerebro IQ (2.ª generación).

  • 1 – El sensor de visión está conectado al cerebro IQ (2.ª generación).

  • 0 – El sensor de visión no está conectado al cerebro IQ (2.ª generación).

Parámetros

Descripción

Este método no tiene parámetros.

// Display a message if the Vision Sensor is detected
if (Vision1.installed()){
  Brain.Screen.print("Vision Sensor Installed!");
}

objetos#

objects devuelve una matriz de propiedades de objetos detectados. Use la matriz para acceder a valores específicos de propiedad de objetos individuales.

Uso predeterminado:
Vision1.objects

Propiedades#

There are eight properties that are included with each object stored in the objects array after takeSnapshot is used.

Algunos valores de propiedad se basan en la posición del objeto detectado en la vista del sensor de visión al momento de usar takeSnapshot. El sensor de visión tiene una resolución de 316 x 212 píxeles.

.existe#

.exists devuelve un entero que indica si el índice existe en la matriz objects o no.

  • 1: El índice existe.

  • 0: El índice no existe.

// Check if at least one object is detected
while (true) {
  // Take a snapshot to check for detected objects.
  Vision1.takeSnapshot(Vision1__BLUEBOX);

  // Clear the screen/reset so that we can display
  // new information.
  Brain.Screen.clearScreen();
  Brain.Screen.setCursor(1, 1);

  // If an object exists, print its location.
  if (Vision1.objects[0].exists) {
    Brain.Screen.print("Center X: %d", Vision1.objects[0].centerX);
  } 
  else {
    Brain.Screen.print("No objects detected.");
  }

  wait(0.5, seconds);
}

.ancho#

.width devuelve el ancho del objeto detectado en píxeles, que es un número entero entre 1 y 316.

// Move towards a blue box until its width is
// larger than 100 pixels
while (true){
  Vision1.takeSnapshot(Vision1__BLUEBOX);

  if (Vision1.objects[0].width < 100) {
    Drivetrain.driveFor(forward, 10, mm);
  } 
  else {
    Drivetrain.stop();
  }

  wait(0.5, seconds);
}

.altura#

.height devuelve la altura del objeto detectado en píxeles, que es un número entero entre 1 y 212.

// Move towards a blue box until its height is
// larger than 100 pixels
while (true){
  Vision1.takeSnapshot(Vision1__BLUEBOX);

  if (Vision1.objects[0].height < 100) {
    Drivetrain.driveFor(forward, 10, mm);
  } 
  else {
    Drivetrain.stop();
  }

  wait(0.5, seconds);
}

.centroX#

.centerX devuelve la coordenada x del centro del objeto detectado en píxeles, que es un número entero entre 0 y 316.

// Turn slowly until a blue box is centered in
// front of the robot
Drivetrain.setTurnVelocity(10,percent);
Drivetrain.turn(right);

while (true){
  Vision1.takeSnapshot(Vision1__BLUEBOX);

  if (Vision1.objects[0].exists){
    if (140 < Vision1.largestObject.centerX && Vision1.largestObject.centerX < 180){
      Drivetrain.stop();
    }
  }
  wait(0.5,seconds);
}

.centerY#

.centerY devuelve la coordenada y del centro del objeto detectado en píxeles, que es un número entero entre 0 y 212.

// Move towards a blue object until its
// center y-coordinate is more than 140 pixels
while (true){
  Vision1.takeSnapshot(Vision1__BLUEBOX);

  if (Vision1.objects[0].exists){
    if (Vision1.largestObject.centerY < 140){
        Drivetrain.drive(forward);
    }
  }
  else{
    Drivetrain.stop();
  }
  wait(0.5,seconds);
}

.ángulo#

.angle devuelve la orientación del objeto detectado en grados, que es un doble entre 0 y 316.

// Turn right or left depending on how the
// configured box code is rotated.
while (true){
  Vision1.takeSnapshot(Vision1__BOXCODE);

  if (Vision1.objects[0].exists){
    if (70 < Vision1.objects[0].angle && Vision1.objects[0].angle < 110){
      Drivetrain.turnFor(right, 45, degrees);
    }
    else if (250 < Vision1.objects[0].angle && Vision1.objects[0].angle < 290){
      Drivetrain.turnFor(left, 45, degrees);
    }
    else{
      Drivetrain.stop();
    }
  }
  wait(0.5,seconds);
}

.origenX#

.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 316.

// Display if a red box is to the
// left or the right
while (true){
  Brain.Screen.clearScreen();
  Brain.Screen.setCursor(1,1);
    
  Vision1.takeSnapshot(Vision1__REDBOX);
    
  if (Vision1.objects[0].exists){
    if (Vision1.objects[0].originX < 160){
      Brain.Screen.print("To the left!");
    }
    else{ 
      Brain.Screen.print("To the right!");
    }
  }
  wait(0.5,seconds);
}

.origenY#

.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 212.

// Display if a red box is close or far
// from the robot.
while (true){
  Brain.Screen.clearScreen();
  Brain.Screen.setCursor(1,1);
    
  Vision1.takeSnapshot(Vision1__REDBOX);

  if (Vision1.objects[0].exists){
    if (Vision1.objects[0].originY < 80){
      Brain.Screen.print("Far");
    }
    else{
      Brain.Screen.print("Close");
    }
  }
  wait(0.5,seconds);
}

Constructores#

Constructors are used to manually create aivision, vision, signature, and code objects, which are necessary for configuring the sensors outside of VEXcode. If fewer arguments are provided, default arguments or function overloading should be used in the constructor definition.

AI Vision Sensor#

aivision creates an AI Vision Sensor.

Default Usage: aivision( int32_t index, uint8_t bright, Args &... sigs )

Parámetros

Descripción

puerto

Which Smart Port the AI Vision Sensor is connected to, from 1 to 12.

sigs

Optional. The name of one or more Color Signature or Color Code objects.

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  // Move forward if an object is detected
  vex::aivision AIVision1(PORT12, aivision::ALL_AIOBJS);
  while (true) {
    AIVision1.takeSnapshot(aivision::ALL_AIOBJS);
    if (AIVision1.objects[0].exists) {
      Drivetrain.driveFor(forward, 50, mm);
    }
    wait(50, msec);
  }
}

Sensor de visión#

vision creates a Vision Sensor.

Uso predeterminado: vision( int32_t index, uint8_t bright, Args &... sigs )

Parámetros

Descripción

puerto

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

brillo

El valor de brillo del sensor de visión, de 10 a 150.

sigs

El nombre de uno o más objetos Firma de color o Código de color creados previamente.

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  vision::signature Vision1__REDBOX = vision::signature (1, 10121, 10757, 10439, -1657, -1223, -1440, 2.5, 1);
  vision Vision1 = vision(PORT1, 50, Vision1__REDBOX);
  while (true) {
    // Take a snapshot to check for detected objects.
    Vision1.takeSnapshot(Vision1__REDBOX);
    // Clear the screen/reset so that we can display new information.
    Brain.Screen.clearScreen();
    Brain.Screen.setCursor(1, 1);
    // If objects were found, print the location.
    if (Vision1.objects[0].exists) {
      Brain.Screen.print("Center X: %d", Vision1.largestObject.centerX);
    } else {
      Brain.Screen.print("no object");
    }
    wait(0.5, seconds);
  }
}

Firma de color#

La función signature crea una firma de color. Se pueden almacenar hasta siete firmas de color diferentes en un sensor de visión simultáneamente.

Default Usage:
signature(index, uMin, uMax, uMean, vMin, vMax, vMean, rgb, type)

Parámetro

Descripción

índice

El índice del objeto signature, de 1 a 7. Nota: La creación de dos objetos signature con el mismo número de índice hará que el segundo objeto creado anule al primero.

uMin

El valor de uMin en la Utilidad de Visión.

uMax

El valor de uMax en la Utilidad de Visión.

uMean

El valor de uMean en la Utilidad de Visión.

vMin

El valor de vMin en la Utilidad de Visión.

vMáx

El valor de vMax en la Utilidad de Visión.

vMean

El valor de vMean en la Utilidad de Visión.

rgb

El valor de rgb en la Utilidad de Visión.

tipo

El valor de type en la Utilidad de Visión.

Para obtener los valores necesarios para crear una Firma de Color, acceda a la Utilidad de Visión. Una vez configurada la Firma de Color, copie los valores de los parámetros desde la ventana de Configuración.

// Construct a vision object Vision1 with two Color
// Signatures, Vision1__redBox and Vision1__blueBox
vision::signature Vision1__redBox = vision::signature (1, 10121, 10757, 10439,-1657, -1223, -1440,2.5, 1);
vision::signature Vision1__blueBox = vision::signature (2, -4479, -3277, -3878,5869, 7509, 6689,2.5, 1);
vision Vision1 = vision (PORT1, 50, Vision1__redBox, Vision1__blueBox);

while (true) {
  // Take a snapshot to check for detected objects
  Vision1.takeSnapshot(Vision1__BLUEBOX);
  // Clear the screen/reset so that we can display
  // new information.
  Brain.Screen.clearScreen();
  Brain.Screen.setCursor(1, 1);
  // If objects were found, print the location
  if (Vision1.objects[0].exists) {
    Brain.Screen.print("Center X: %d", Vision1.largestObject.centerX);
  } else {
    Brain.Screen.print("no object");
  }
  wait(0.5, seconds);
}

Código de colores#

«Código» crea un código de color. Requiere al menos dos firmas de color predefinidas para su uso. Se pueden almacenar hasta ocho códigos de color diferentes en un sensor de visión simultáneamente.

Default Usage:
code(sig1, sig2)

Overloads:

  • código(sig1, sig2, sig3)

  • código(sig1, sig2, sig3, sig4)

  • código(sig1, sig2, sig3, sig4, sig5)

Parámetros

Descripción

sig1

Un objeto de firma creado previamente, o el índice int32_t de un objeto de firma creado previamente.

sig2

Un objeto de firma creado previamente, o el índice int32_t de un objeto de firma creado previamente.

sig3

Un objeto de firma creado previamente, o el índice int32_t de un objeto de firma creado previamente.

sig4

Un objeto de firma creado previamente, o el índice int32_t de un objeto de firma creado previamente.

sig5

Un objeto de firma creado previamente, o el índice int32_t de un objeto de firma creado previamente.

int main() {
  // Initializing Robot Configuration. DO NOT REMOVE!
  vexcodeInit();
  vision::signature Vision1__redBox = vision::signature(1, 10121, 10757, 10439, -1657, -1223, -1440, 2.5, 1);
  vision::signature Vision1__blueBox = vision::signature(2, -4479, -3277, -3878, 5869, 7509, 6689, 2.5, 1);
  vision::code Vision1__boxCode = vision::code(Vision1__redBox, Vision1__blueBox);
  vision Vision1 = vision(PORT1, 50, Vision1__redBox, Vision1__blueBox);
  // Turn right or left depending on how the
  // configured box code is rotated
  while (true) {
    Vision1.takeSnapshot(Vision1__BOXCODE);
    if (Vision1.objects[0].exists) {
      int angle = Vision1.objects[0].angle;
      if (angle > 70 && angle < 110) {
        Drivetrain.turnFor(right, 45, degrees);
      }
      else if (angle > 250 && angle < 290) {
        Drivetrain.turnFor(left, 45, degrees);
      }
      else {
        Drivetrain.stop();
      }
    }
    wait(0.5, seconds);
  }
}