Detecta etiquetas en una imagen mediante la API de Cloud Vision

Esta guía de inicio rápido te muestra cómo hacer lo siguiente:

  • Crear un bucket de Cloud Storage
  • Sube tu imagen a Cloud Storage y habilita el acceso público al archivo.
  • Realizar una solicitud a la API de Vision con dicha imagen

Completar estos pasos lleva unos 5 minutos. Puedes almacenar hasta 5 GB de datos en Cloud Storage sin cargo y realizar hasta 1000 solicitudes de función por mes a Vision API sin cargo.

Antes de comenzar

Si aún no lo hiciste, sigue las siguientes instrucciones para configurar tu proyecto y crear un bucket de Cloud Storage.

Configura tu proyecto

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Vision API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Vision API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  8. Cree un bucket de Cloud Storage

    1. In the Google Cloud console, go to the Cloud Storage Buckets page.

      Go to Buckets

    2. Click Create.
    3. On the Create a bucket page, enter your bucket information. To go to the next step, click Continue.
      1. For Name your bucket, enter a unique bucket name. Don't include sensitive information in the bucket name, because the bucket namespace is global and publicly visible.
      2. In the Choose where to store your data section, do the following:
        1. Select a Location type.
        2. Choose a location where your bucket's data is permanently stored from the Location type drop-down menu.
        3. To set up cross-bucket replication, select Add cross-bucket replication via Storage Transfer Service and follow these steps:

          Set up cross-bucket replication

          1. In the Bucket menu, select a bucket.
          2. In the Replication settings section, click Configure to configure settings for the replication job.

            The Configure cross-bucket replication pane appears.

            • To filter objects to replicate by object name prefix, enter a prefix that you want to include or exclude objects from, then click Add a prefix.
            • To set a storage class for the replicated objects, select a storage class from the Storage class menu. If you skip this step, the replicated objects will use the destination bucket's storage class by default.
            • Click Done.
      3. In the Choose how to store your data section, do the following:
        1. In the Set a default class section, select the following: Standard.
        2. To enable hierarchical namespace, in the Optimize storage for data-intensive workloads section, select Enable hierarchical namespace on this bucket.
      4. In the Choose how to control access to objects section, select whether or not your bucket enforces public access prevention, and select an access control method for your bucket's objects.
      5. In the Choose how to protect object data section, do the following:
        • Select any of the options under Data protection that you want to set for your bucket.
          • To enable soft delete, click the Soft delete policy (For data recovery) checkbox, and specify the number of days you want to retain objects after deletion.
          • To set Object Versioning, click the Object versioning (For version control) checkbox, and specify the maximum number of versions per object and the number of days after which the noncurrent versions expire.
          • To enable the retention policy on objects and buckets, click the Retention (For compliance) checkbox, and then do the following:
            • To enable Object Retention Lock, click the Enable object retention checkbox.
            • To enable Bucket Lock, click the Set bucket retention policy checkbox, and choose a unit of time and a length of time for your retention period.
        • To choose how your object data will be encrypted, expand the Data encryption section (), and select a Data encryption method.
    4. Click Create.

    Realiza una solicitud a Cloud Vision

    1. Guarda una versión local del archivo de imagen de muestra (demo-img.jpg).

    2. En la Google Cloud consola, ve a la página Buckets de Cloud Storage.

      Ir a Buckets

    3. Selecciona el bucket que creaste en la sección anterior.

    4. Haz clic en Subir archivos y selecciona la versión local del archivo demo-img.jpg para subirlo a tu bucket de Cloud Storage.

      El botón Subir archivos
      Este es el archivo de imagen que acabas de subir:
      Dos mujeres andando en bicicleta en Yakarta.
      Crédito de la imagen: Rohiim Ariful en Unsplash.

    5. Una vez que se haya subido el archivo y aparezca en el bucket de Cloud Storage, comparte la imagen públicamente.

    6. En la sección Prueba este método, completa la plantilla interactiva del Explorador de APIs mediante el reemplazo de cloud-samples-data/vision en el campo image.source.imageUri con el nombre del bucket de Cloud Storage en el que subiste el archivo demo-img.jpg. El cuerpo de la solicitud se debe ver de la siguiente manera:

      {
        "requests": [
          {
            "features": [
              {
                "type": "LABEL_DETECTION"
              }
            ],
            "image": {
              "source": {
                "imageUri": "gs://cloud-samples-data/vision/demo-img.jpg"
              }
            }
          }
        ]
      }

    7. Haz clic en Ejecutar para enviar la solicitud al servicio. La respuesta JSON aparece después del cuerpo de la solicitud.

    ¡Felicitaciones! Realizaste tu primera solicitud images.annotate a Cloud Vision.

    Limpia

    Para evitar cargos Google Cloud innecesarios, usa la Google Cloud consola para borrar tu bucket de Cloud Storage (y tu proyecto) si no los necesitas.

    ¿Qué sigue?

    • Ve una lista de todos los tipos de funciones y sus usos.
    • Comienza a usar la API de Vision en el idioma que prefieras mediante una biblioteca cliente de esta API.
    • Usa las guías prácticas para obtener más información sobre funciones específicas, ver ejemplos de anotaciones y obtener anotaciones para un archivo o una imagen individuales.
    • Obtén más información sobre la anotación por lotes para imágenes y archivos (PDF, TIFF y GIF).
    • Explora una lista completa de las muestras de código de la biblioteca cliente.