Obtén y enumera recursos

En cualquier momento, puedes enumerar y obtener cualquier conjunto de productos, producto o recursos de imagen de referencia que tengas.

Enumera conjuntos de productos

En esta sección, se describe cómo recuperar una lista de todos tus conjuntos de productos.

LÍNEA DE CMD Y REST

Antes de usar cualquiera de los siguientes datos de solicitud, realiza estos reemplazos:

  • project-id: El ID de tu proyecto de GCP
  • location-id: Un identificador de ubicación válido. Los identificadores de ubicación válidos son: us-west1, us-east1, europe-west1 y asia-east1.

Método HTTP y URL:

GET https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets

Para enviar tu solicitud, elige una de estas opciones:

curl

Ejecuta el siguiente comando:

curl -X GET \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets

PowerShell

Ejecuta el siguiente comando:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets" | Select-Object -Expand Content

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

C#

        private static object ListProductsSet(ListProductSetsOptions opts)
        {
            var client = ProductSearchClient.Create();
            var request = new ListProductSetsRequest
            {
                // A resource that represents Google Cloud Platform location
                ParentAsLocationName = new LocationName(opts.ProjectID, opts.ComputeRegion)
            };

            // List all the product sets available in the region.
            var response = client.ListProductSets(request);

            foreach (var productSet in response)
            {
                var id = productSet.Name.Split("/").Last();
                Console.WriteLine($"Product set name: {productSet.DisplayName}");
                Console.WriteLine($"Product set ID: {id}");
                Console.WriteLine($"Product set index time:");
                Console.WriteLine($"\tseconds: {productSet.IndexTime.Seconds}");
                Console.WriteLine($"\tnanos: {productSet.IndexTime.Nanos}");
            }

            return 0;
        }

Go


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"google.golang.org/api/iterator"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

// listProductSets lists product sets.
func listProductSets(w io.Writer, projectID string, location string) error {
	ctx := context.Background()
	c, err := vision.NewProductSearchClient(ctx)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %v", err)
	}
	defer c.Close()

	req := &visionpb.ListProductSetsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
	}

	it := c.ListProductSets(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Next: %v", err)
		}

		fmt.Fprintf(w, "Product set name: %s\n", resp.Name)
		fmt.Fprintf(w, "Product set display name: %s\n", resp.DisplayName)
		fmt.Fprintf(w, "Product set index time:\n")
		fmt.Fprintf(w, "seconds: %d\n", resp.IndexTime.Seconds)
		fmt.Fprintf(w, "nanos: %d\n", resp.IndexTime.Nanos)
	}

	return nil
}

Java

/**
 * List all product sets
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @throws IOException - on I/O errors.
 */
public static void listProductSets(String projectId, String computeRegion) throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {
    // A resource that represents Google Cloud Platform location.
    String formattedParent = ProductSearchClient.formatLocationName(projectId, computeRegion);
    // List all the product sets available in the region.
    for (ProductSet productSet : client.listProductSets(formattedParent).iterateAll()) {
      // Display the product set information
      System.out.println(String.format("Product set name: %s", productSet.getName()));
      System.out.println(
          String.format(
              "Product set id: %s",
              productSet.getName().substring(productSet.getName().lastIndexOf('/') + 1)));
      System.out.println(
          String.format("Product set display name: %s", productSet.getDisplayName()));
      System.out.println("Product set index time:");
      System.out.println(String.format("\tseconds: %s", productSet.getIndexTime().getSeconds()));
      System.out.println(String.format("\tnanos: %s", productSet.getIndexTime().getNanos()));
    }
  }
}

Node.js

// Imports the Google Cloud client library
const vision = require('@google-cloud/vision');

// Creates a client
const client = new vision.ProductSearchClient();

async function listProductSets() {
  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'Your Google Cloud project Id';
  // const location = 'A compute region name';

  // Resource path that represents Google Cloud Platform location.
  const locationPath = client.locationPath(projectId, location);

  const [productSets] = await client.listProductSets({parent: locationPath});
  productSets.forEach(productSet => {
    console.log(`Product Set name: ${productSet.name}`);
    console.log(`Product Set display name: ${productSet.displayName}`);
  });
}
listProductSets();

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;

/**
 * List all product set
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 */
function product_set_list($projectId, $location)
{
    $client = new ProductSearchClient();

    # a resource that represents Google Cloud Platform location.
    $locationPath = $client->locationName($projectId, $location);

    # a resource that represents Google Cloud Platform location.
    $productSets = $client->listProductSets($locationPath);

    # display the product set information.
    foreach ($productSets->iterateAllElements() as $productSet) {
        $name = $productSet->getName();
        $nameArray = explode('/', $name);
        $indexTime = $productSet->getIndexTime();

        printf('Product set name: %s' . PHP_EOL, $name);
        printf('Product set id: %s' . PHP_EOL, end($nameArray));
        printf('Product set display name: %s' . PHP_EOL, $productSet->getDisplayName());
        printf('Product set index time: %d seconds %d nanos' . PHP_EOL, $indexTime->getSeconds(), $indexTime->getNanos());
        print(PHP_EOL);
    }

    $client->close();
}

Python

from google.cloud import vision

def list_product_sets(project_id, location):
    """List all product sets.
    Args:
        project_id: Id of the project.
        location: A compute region name.
    """
    client = vision.ProductSearchClient()

    # A resource that represents Google Cloud Platform location.
    location_path = f"projects/{project_id}/locations/{location}"

    # List all the product sets available in the region.
    product_sets = client.list_product_sets(parent=location_path)

    # Display the product set information.
    for product_set in product_sets:
        print('Product set name: {}'.format(product_set.name))
        print('Product set id: {}'.format(product_set.name.split('/')[-1]))
        print('Product set display name: {}'.format(product_set.display_name))
        print('Product set index time: ')
        print(product_set.index_time)

Ruby

require "google/cloud/vision"

def product_search_list_product_sets project_id = "your-project-id",
                                     location   = "us-west1"

  client = Google::Cloud::Vision.product_search

  location_path = client.location_path project: project_id, location: location

  puts "Product Sets in location #{location}:"
  client.list_product_sets(parent: location_path).each do |product_set|
    puts "\t#{product_set.name}"
  end
end

Obtén un solo conjunto de productos

Puedes obtener un solo conjunto de productos para usar o modificar.

LÍNEA DE CMD Y REST

Antes de usar cualquiera de los siguientes datos de solicitud, realiza estos reemplazos:

  • project-id: El ID de tu proyecto de GCP
  • location-id: Un identificador de ubicación válido. Los identificadores de ubicación válidos son: us-west1, us-east1, europe-west1 y asia-east1.
  • product-set-id: Es el ID del conjunto de productos en el que deseas ejecutar la operación.

Método HTTP y URL:

GET https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets/product-set-id

Para enviar tu solicitud, elige una de estas opciones:

curl

Ejecuta el siguiente comando:

curl -X GET \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets/product-set-id

PowerShell

Ejecuta el siguiente comando:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets/product-set-id" | Select-Object -Expand Content

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "name": "projects/project-id/locations/location-id/productSets/product-set-id",
  "displayName": "display-name",
  "indexTime": "2019-09-04T15:33:43.581861690Z",
  "indexError": {}
}

C#

        private static object GetProductSet(GetProductSetOptions opts)
        {
            var client = ProductSearchClient.Create();
            var request = new GetProductSetRequest
            {
                // Get the full path of the product set.
                ProductSetName = new ProductSetName(opts.ProjectID,
                                                    opts.ComputeRegion,
                                                    opts.ProductSetId)
            };

            // Get the complete detail of the product set.
            var productSet = client.GetProductSet(request);

            var id = productSet.Name.Split("/").Last();
            Console.WriteLine($"Product set name: {productSet.DisplayName}");
            Console.WriteLine($"Product set ID: {id}");
            Console.WriteLine($"Product set index time:");
            Console.WriteLine($"\tseconds: {productSet.IndexTime.Seconds}");
            Console.WriteLine($"\tnanos: {productSet.IndexTime.Nanos}");

            return 0;
        }

Go


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

// getProductSet gets a product set.
func getProductSet(w io.Writer, projectID string, location string, productSetID string) error {
	ctx := context.Background()
	c, err := vision.NewProductSearchClient(ctx)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %v", err)
	}
	defer c.Close()

	req := &visionpb.GetProductSetRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/productSets/%s", projectID, location, productSetID),
	}

	resp, err := c.GetProductSet(ctx, req)
	if err != nil {
		return fmt.Errorf("GetProductSet: %v", err)
	}

	fmt.Fprintf(w, "Product set name: %s\n", resp.Name)
	fmt.Fprintf(w, "Product set display name: %s\n", resp.DisplayName)
	fmt.Fprintf(w, "Product set index time:\n")
	fmt.Fprintf(w, "seconds: %d\n", resp.IndexTime.Seconds)
	fmt.Fprintf(w, "nanos: %d\n", resp.IndexTime.Nanos)

	return nil
}

Java

/**
 * Get info about the product set.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productSetId - Id of the product set.
 * @throws IOException - on I/O errors.
 */
public static void getProductSet(String projectId, String computeRegion, String productSetId)
    throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // Get the full path of the product set.
    String formattedName =
        ProductSearchClient.formatProductSetName(projectId, computeRegion, productSetId);
    // Get complete detail of the product set.
    ProductSet productSet = client.getProductSet(formattedName);
    // Display the product set information
    System.out.println(String.format("Product set name: %s", productSet.getName()));
    System.out.println(
        String.format(
            "Product set id: %s",
            productSet.getName().substring(productSet.getName().lastIndexOf('/') + 1)));
    System.out.println(
        String.format("Product set display name: %s", productSet.getDisplayName()));
    System.out.println("Product set index time:");
    System.out.println(String.format("\tseconds: %s", productSet.getIndexTime().getSeconds()));
    System.out.println(String.format("\tnanos: %s", productSet.getIndexTime().getNanos()));
  }
}

Node.js

// Imports the Google Cloud client library
const vision = require('@google-cloud/vision');

// Creates a client
const client = new vision.ProductSearchClient();

async function getProductSet() {
  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'Your Google Cloud project Id';
  // const location = 'A compute region name';
  // const productSetId = 'Id of the product set';

  // Resource path that represents Google Cloud Platform location.
  const productSetPath = client.productSetPath(
    projectId,
    location,
    productSetId
  );

  const [productSet] = await client.getProductSet({name: productSetPath});
  console.log(`Product Set name: ${productSet.name}`);
  console.log(`Product Set display name: ${productSet.displayName}`);
}
getProductSet();

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;

/**
 * Get information about a product set
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productSetId ID of the product
 */
function product_set_get($projectId, $location, $productSetId)
{
    $client = new ProductSearchClient();

    # get the name of the product set
    $productSetPath = $client->productSetName($projectId, $location, $productSetId);

    # get complete detail of the product set
    $productSet = $client->getProductSet($productSetPath);

    # display the product set information.
    $name = $productSet->getName();
    $nameArray = explode('/', $name);
    $indexTime = $productSet->getIndexTime();

    printf('Product set name: %s' . PHP_EOL, $name);
    printf('Product set id: %s' . PHP_EOL, end($nameArray));
    printf('Product set display name: %s' . PHP_EOL, $productSet->getDisplayName());
    printf('Product set index time: %d seconds %d nanos' . PHP_EOL, $indexTime->getSeconds(), $indexTime->getNanos());
    $client->close();
}

Python

from google.cloud import vision

def get_product_set(project_id, location, product_set_id):
    """Get info about the product set.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_set_id: Id of the product set.
    """
    client = vision.ProductSearchClient()

    # Get the full path of the product set.
    product_set_path = client.product_set_path(
        project=project_id, location=location,
        product_set=product_set_id)

    # Get complete detail of the product set.
    product_set = client.get_product_set(name=product_set_path)

    # Display the product set information.
    print('Product set name: {}'.format(product_set.name))
    print('Product set id: {}'.format(product_set.name.split('/')[-1]))
    print('Product set display name: {}'.format(product_set.display_name))
    print('Product set index time: ')
    print(product_set.index_time)

Ruby

require "google/cloud/vision"

def product_search_get_product_set project_id     = "your-project-id",
                                   location       = "us-west1",
                                   product_set_id = "your-product-set-id"

  client = Google::Cloud::Vision.product_search

  product_set_path = client.product_set_path project:     project_id,
                                             location:    location,
                                             product_set: product_set_id

  product_set = client.get_product_set name: product_set_path

  puts "Product set name: #{product_set.name}"
  puts "Product set display name: #{product_set.display_name}"
end

Enumera productos

Puedes ver todos los productos en un proyecto de Google Cloud Platform o en un conjunto de productos específico.

Enumera todos los productos de un proyecto

En el siguiente ejemplo, se muestra cómo enumerar productos en un proyecto.

LÍNEA DE CMD Y REST

Antes de usar cualquiera de los siguientes datos de solicitud, realiza estos reemplazos:

  • project-id: El ID de tu proyecto de GCP
  • location-id: Un identificador de ubicación válido. Los identificadores de ubicación válidos son: us-west1, us-east1, europe-west1 y asia-east1.

Método HTTP y URL:

GET https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products

Para enviar tu solicitud, elige una de estas opciones:

curl

Ejecuta el siguiente comando:

curl -X GET \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products

PowerShell

Ejecuta el siguiente comando:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products" | Select-Object -Expand Content

Si la solicitud se completa de forma correcta, el servidor muestra un código de estado HTTP 200 OK y la respuesta en formato JSON:

Deberías ver un resultado similar al siguiente. Ten en cuenta que la cantidad de productos que se muestran se limita a 10 por vez, y se proporciona un nextPageToken si hay más páginas.

Si se muestra un nextPageToken, puedes usar el token para obtener la siguiente página de los resultados de productos. Usa el nextPageToken del JSON de respuesta (jMGjEqhXMtN95vZz2g en este ejemplo) como una consulta de pageToken anexada a la URL de la solicitud:

https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products?pageToken=jMGjEqhXMtN95vZz2g

C#

private static int ListProducts(ListProductsOptions opts)
{
    var client = ProductSearchClient.Create();
    var request = new ListProductsRequest
    {
        // A resource that represents Google Cloud Platform location.
        ParentAsLocationName = new LocationName(opts.ProjectID,
                                                opts.ComputeRegion)
    };

    var products = client.ListProducts(request);
    foreach (var product in products)
    {
        var productId = product.Name.Split("/").Last();
        Console.WriteLine($"\nProduct name: {product.Name}");
        Console.WriteLine($"Product id: {productId}");
        Console.WriteLine($"Product display name: {product.DisplayName}");
        Console.WriteLine($"Product category: {product.ProductCategory}");
        Console.WriteLine($"Product labels:");
        foreach (var label in product.ProductLabels)
        {
            Console.WriteLine($"\tLabel: {label.ToString()}");
        }
    }
    return 0;
}

Go


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"google.golang.org/api/iterator"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

// listProducts lists products.
func listProducts(w io.Writer, projectID string, location string) error {
	ctx := context.Background()
	c, err := vision.NewProductSearchClient(ctx)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %v", err)
	}
	defer c.Close()

	req := &visionpb.ListProductsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
	}

	it := c.ListProducts(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Next: %v", err)
		}

		fmt.Fprintf(w, "Product name: %s\n", resp.Name)
		fmt.Fprintf(w, "Product display name: %s\n", resp.DisplayName)
		fmt.Fprintf(w, "Product category: %s\n", resp.ProductCategory)
		fmt.Fprintf(w, "Product labels: %s\n", resp.ProductLabels)
	}

	return nil
}

Java

/**
 * List all products.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @throws IOException - on I/O errors.
 */
public static void listProducts(String projectId, String computeRegion) throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // A resource that represents Google Cloud Platform location.
    String formattedParent = ProductSearchClient.formatLocationName(projectId, computeRegion);

    // List all the products available in the region.
    for (Product product : client.listProducts(formattedParent).iterateAll()) {
      // Display the product information
      System.out.println(String.format("\nProduct name: %s", product.getName()));
      System.out.println(
          String.format(
              "Product id: %s",
              product.getName().substring(product.getName().lastIndexOf('/') + 1)));
      System.out.println(String.format("Product display name: %s", product.getDisplayName()));
      System.out.println(String.format("Product category: %s", product.getProductCategory()));
      System.out.println("Product labels:");
      System.out.println(
          String.format("Product labels: %s", product.getProductLabelsList().toString()));
    }
  }
}

Node.js

// Imports the Google Cloud client library
const vision = require('@google-cloud/vision');

// Creates a client
const client = new vision.ProductSearchClient();

async function listProducts() {
  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'Your Google Cloud project Id';
  // const location = 'A compute region name';

  // Resource path that represents Google Cloud Platform location.
  const locationPath = client.locationPath(projectId, location);

  const [products] = await client.listProducts({parent: locationPath});
  products.forEach(product => {
    console.log(`Product name: ${product.name}`);
    console.log(`Product id: ${product.name.split('/').pop()}`);
    console.log(`Product display name: ${product.displayName}`);
    console.log(`Product description: ${product.description}`);
    console.log(`Product category: ${product.productCategory}`);
    if (product.productLabels.length) {
      console.log('Product labels:');
      product.productLabels.forEach(productLabel => {
        console.log(`${productLabel.key}: ${productLabel.value}`);
      });
    }
  });
}
listProducts();

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;

/**
 * List all products
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 */
function product_list($projectId, $location)
{
    $client = new ProductSearchClient();

    # a resource that represents Google Cloud Platform location.
    $locationPath = $client->locationName($projectId, $location);

    # list all the products available in the region.
    $products =$client->listProducts($locationPath);

    # display the product information.
    foreach ($products->iterateAllElements() as $product) {
        $name = $product->getName();
        $nameArray = explode('/', $name);

        printf('Product name: %s' . PHP_EOL, $name);
        printf('Product id: %s' . PHP_EOL, end($nameArray));
        printf('Product display name: %s' . PHP_EOL, $product->getDisplayName());
        printf('Product description: %s' . PHP_EOL, $product->getDescription());
        printf('Product category: %s' . PHP_EOL, $product->getProductCategory());
        print('Product labels: ' . PHP_EOL);
        foreach ($product->getProductLabels() as $label) {
            printf('%s : %s' . PHP_EOL, $label->getKey(), $label->getValue());
        }
        print(PHP_EOL);
    }
    $client->close();
}

Python

from google.cloud import vision
from google.protobuf import field_mask_pb2 as field_mask

def list_products(project_id, location):
    """List all products.
    Args:
        project_id: Id of the project.
        location: A compute region name.
    """
    client = vision.ProductSearchClient()

    # A resource that represents Google Cloud Platform location.
    location_path = f"projects/{project_id}/locations/{location}"

    # List all the products available in the region.
    products = client.list_products(parent=location_path)

    # Display the product information.
    for product in products:
        print('Product name: {}'.format(product.name))
        print('Product id: {}'.format(product.name.split('/')[-1]))
        print('Product display name: {}'.format(product.display_name))
        print('Product description: {}'.format(product.description))
        print('Product category: {}'.format(product.product_category))
        print('Product labels: {}\n'.format(product.product_labels))

Ruby

require "google/cloud/vision"

def product_search_list_products project_id = "your-project-id",
                                 location   = "us-west1"

  client = Google::Cloud::Vision.product_search

  location_path = client.location_path project: project_id, location: location

  puts "Products in location #{location}:"
  client.list_products(parent: location_path).each do |product|
    puts "\t#{product.name}"
  end
end

Enumera todos los productos de un conjunto de productos

En el siguiente ejemplo, se muestra cómo enumerar productos en un conjunto de productos específico.

LÍNEA DE CMD Y REST

Antes de usar cualquiera de los siguientes datos de solicitud, realiza estos reemplazos:

  • project-id: El ID de tu proyecto de GCP
  • location-id: Un identificador de ubicación válido. Los identificadores de ubicación válidos son: us-west1, us-east1, europe-west1 y asia-east1.
  • product-set-id: Es el ID del conjunto de productos en el que deseas ejecutar la operación.

Método HTTP y URL:

GET https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets/product-set-id/products

Para enviar tu solicitud, elige una de estas opciones:

curl

Ejecuta el siguiente comando:

curl -X GET \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets/product-set-id/products

PowerShell

Ejecuta el siguiente comando:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets/product-set-id/products" | Select-Object -Expand Content

Si la solicitud se completa de forma correcta, el servidor muestra un código de estado HTTP 200 OK y la respuesta en formato JSON:

Deberías ver un resultado similar al siguiente. Ten en cuenta que la cantidad de productos que se muestran se limita a 10 por vez, y se proporciona un nextPageToken si hay más páginas.

Si se muestra un nextPageToken, puedes usar el token para obtener la siguiente página de los resultados de productos. Usa el nextPageToken del JSON de respuesta (e5nEGpoVEZqlBbZRhQ en este ejemplo) como una consulta de pageToken anexada a la URL de la solicitud:

https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products?pageToken=e5nEGpoVEZqlBbZRhQ

C#

private static int ListProductsInProductSet(ListProductsInProductSetOptions opts)
{
    var client = ProductSearchClient.Create();
    var request = new ListProductsInProductSetRequest
    {
        // Get the full path of the product set.
        ProductSetName = new ProductSetName(opts.ProjectID,
                                           opts.ComputeRegion,
                                           opts.ProductSetId)
    };

    var products = client.ListProductsInProductSet(request);
    Console.WriteLine("Products in product set:");
    foreach (var product in products)
    {
        Console.WriteLine($"Product name: {product.Name}");
        Console.WriteLine($"Product id: {product.Name.Split("/").Last()}");
        Console.WriteLine($"Product display name: {product.DisplayName}");
        Console.WriteLine($"Product description: {product.Description}");
        Console.WriteLine($"Product category: {product.ProductCategory}");
        Console.WriteLine($"Product labels:");
        foreach (var label in product.ProductLabels)
        {
            Console.WriteLine($"Label: {label}");
        }
    }

    return 0;
}

Go


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"google.golang.org/api/iterator"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

// listProductsInProductSet lists products in a product set.
func listProductsInProductSet(w io.Writer, projectID string, location string, productSetID string) error {
	ctx := context.Background()
	c, err := vision.NewProductSearchClient(ctx)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %v", err)
	}
	defer c.Close()

	req := &visionpb.ListProductsInProductSetRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/productSets/%s", projectID, location, productSetID),
	}

	it := c.ListProductsInProductSet(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Next: %v", err)
		}

		fmt.Fprintf(w, "Product name: %s\n", resp.Name)
		fmt.Fprintf(w, "Product display name: %s\n", resp.DisplayName)
		fmt.Fprintf(w, "Product category: %s\n", resp.ProductCategory)
		fmt.Fprintf(w, "Product labels: %s\n", resp.ProductLabels)
	}

	return nil
}

Java

/**
 * List all products in a product set.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productSetId - Id of the product set.
 * @throws IOException - on I/O errors.
 */
public static void listProductsInProductSet(
    String projectId, String computeRegion, String productSetId) throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // Get the full path of the product set.
    String formattedName =
        ProductSearchClient.formatProductSetName(projectId, computeRegion, productSetId);
    // List all the products available in the product set.
    for (Product product : client.listProductsInProductSet(formattedName).iterateAll()) {
      // Display the product information
      System.out.println(String.format("Product name: %s", product.getName()));
      System.out.println(
          String.format(
              "Product id: %s",
              product.getName().substring(product.getName().lastIndexOf('/') + 1)));
      System.out.println(String.format("Product display name: %s", product.getDisplayName()));
      System.out.println(String.format("Product description: %s", product.getDescription()));
      System.out.println(String.format("Product category: %s", product.getProductCategory()));
      System.out.println("Product labels: ");
      for (Product.KeyValue element : product.getProductLabelsList()) {
        System.out.println(String.format("%s: %s", element.getKey(), element.getValue()));
      }
    }
  }
}

Node.js

const vision = require('@google-cloud/vision');

const client = new vision.ProductSearchClient();

async function listProductsInProductSet() {
  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'Your Google Cloud project Id';
  // const location = 'A compute region name';
  // const productSetId = 'Id of the product set';
  const productSetPath = client.productSetPath(
    projectId,
    location,
    productSetId
  );
  const request = {
    name: productSetPath,
  };

  const [products] = await client.listProductsInProductSet(request);
  products.forEach(product => {
    console.log(`Product name: ${product.name}`);
    console.log(`Product display name: ${product.displayName}`);
  });
}
listProductsInProductSet();

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;

/**
 * Create a product set
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productSetId ID of the product set
 */
function product_set_list_products($projectId, $location, $productSetId)
{
    $client = new ProductSearchClient();

    # get the name of the product set
    $productSetPath = $client->productSetName($projectId, $location, $productSetId);

    # list all the products available in the product set.
    $products = $client->listProductsInProductSet($productSetPath);

    # display the product information.
    foreach ($products->iterateAllElements() as $product) {
        $name = $product->getName();
        $nameArray = explode('/', $name);

        printf('Product name: %s' . PHP_EOL, $name);
        printf('Product id: %s' . PHP_EOL, end($nameArray));
        printf('Product display name: %s' . PHP_EOL, $product->getDisplayName());
        printf('Product description: %s' . PHP_EOL, $product->getDescription());
        printf('Product category: %s' . PHP_EOL, $product->getProductCategory());
        print('Product labels: ' . PHP_EOL);
        foreach ($product->getProductLabels() as $label) {
            printf('%s : %s' . PHP_EOL, $label->getKey(), $label->getValue());
        }
        print(PHP_EOL);
    }
    $client->close();
}

Python

def list_products_in_product_set(
        project_id, location, product_set_id):
    """List all products in a product set.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_set_id: Id of the product set.
    """
    client = vision.ProductSearchClient()

    # Get the full path of the product set.
    product_set_path = client.product_set_path(
        project=project_id, location=location,
        product_set=product_set_id)

    # List all the products available in the product set.
    products = client.list_products_in_product_set(name=product_set_path)

    # Display the product information.
    for product in products:
        print('Product name: {}'.format(product.name))
        print('Product id: {}'.format(product.name.split('/')[-1]))
        print('Product display name: {}'.format(product.display_name))
        print('Product description: {}'.format(product.description))
        print('Product category: {}'.format(product.product_category))
        print('Product labels: {}'.format(product.product_labels))

Ruby

require "google/cloud/vision"

def product_search_list_products_in_product_set \
    project_id     = "your-project-id",
    location       = "us-west1",
    product_set_id = "your-product-set-id"

  client = Google::Cloud::Vision.product_search

  product_set_path = client.product_set_path project:     project_id,
                                             location:    location,
                                             product_set: product_set_id

  puts "Products in product set #{product_set_id}:"
  client.list_products_in_product_set(name: product_set_path).each do |product|
    puts "\t#{product.name}"
  end
end

Obtén un solo producto

Puedes obtener también un solo producto para usar o modificar.

LÍNEA DE CMD Y REST

Antes de usar cualquiera de los siguientes datos de solicitud, realiza estos reemplazos:

  • project-id: El ID de tu proyecto de GCP
  • location-id: Un identificador de ubicación válido. Los identificadores de ubicación válidos son los siguientes: us-west1, us-east1, europe-west1 y asia-east1
  • product-id: El ID del producto asociado con una imagen de referencia. Este ID se establece de forma aleatoria, o el usuario lo especifica al momento de crear el producto.

Método HTTP y URL:

GET https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id

Para enviar tu solicitud, elige una de estas opciones:

curl

Ejecuta el siguiente comando:

curl -X GET \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id

PowerShell

Ejecuta el siguiente comando:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id" | Select-Object -Expand Content

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "name": "projects/project-id/locations/location-id/products/product-id",
  "displayName": " ",
  "productCategory": "apparel-v2",
  "productLabels": [
    {
      "key": "style",
      "value": "women"
    },
    {
      "key": "category",
      "value": "dress"
    }
  ]
}

C#

private static int GetProduct(GetProductOptions opts)
{
    var client = ProductSearchClient.Create();
    var request = new GetProductRequest
    {
        // Get the full path of the product.
        ProductName = new ProductName(opts.ProjectID,
                                      opts.ComputeRegion,
                                      opts.ProductID)
    };

    var product = client.GetProduct(request);

    var productId = product.Name.Split("/").Last();
    Console.WriteLine($"\nProduct name: {product.Name}");
    Console.WriteLine($"Product id: {productId}");
    Console.WriteLine($"Product display name: {product.DisplayName}");
    Console.WriteLine($"Product category: {product.ProductCategory}");
    Console.WriteLine($"Product labels:");
    foreach (var label in product.ProductLabels)
    {
        Console.WriteLine($"\tLabel: {label.ToString()}");
    }
    return 0;
}

Go


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

// getProduct gets a product.
func getProduct(w io.Writer, projectID string, location string, productID string) error {
	ctx := context.Background()
	c, err := vision.NewProductSearchClient(ctx)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %v", err)
	}
	defer c.Close()

	req := &visionpb.GetProductRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/products/%s", projectID, location, productID),
	}

	resp, err := c.GetProduct(ctx, req)
	if err != nil {
		return fmt.Errorf("GetProduct: %v", err)
	}

	fmt.Fprintf(w, "Product name: %s\n", resp.Name)
	fmt.Fprintf(w, "Product display name: %s\n", resp.DisplayName)
	fmt.Fprintf(w, "Product category: %s\n", resp.ProductCategory)
	fmt.Fprintf(w, "Product labels: %s\n", resp.ProductLabels)

	return nil
}

Java

/**
 * Get information about a product.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productId - Id of the product.
 * @throws IOException - on I/O errors.
 */
public static void getProduct(String projectId, String computeRegion, String productId)
    throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // Get the full path of the product.
    String formattedName =
        ProductSearchClient.formatProductName(projectId, computeRegion, productId);
    // Get complete detail of the product.
    Product product = client.getProduct(formattedName);
    // Display the product information
    System.out.println(String.format("Product name: %s", product.getName()));
    System.out.println(
        String.format(
            "Product id: %s",
            product.getName().substring(product.getName().lastIndexOf('/') + 1)));
    System.out.println(String.format("Product display name: %s", product.getDisplayName()));
    System.out.println(String.format("Product description: %s", product.getDescription()));
    System.out.println(String.format("Product category: %s", product.getProductCategory()));
    System.out.println(String.format("Product labels: "));
    for (Product.KeyValue element : product.getProductLabelsList()) {
      System.out.println(String.format("%s: %s", element.getKey(), element.getValue()));
    }
  }
}

Node.js

// Imports the Google Cloud client library
const vision = require('@google-cloud/vision');

// Creates a client
const client = new vision.ProductSearchClient();

async function getProduct() {
  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'Your Google Cloud project Id';
  // const location = 'A compute region name';
  // const productId = 'Id of the product';

  // Resource path that represents Google Cloud Platform location.
  const productPath = client.productPath(projectId, location, productId);

  const [product] = await client.getProduct({name: productPath});
  console.log(`Product name: ${product.name}`);
  console.log(`Product id: ${product.name.split('/').pop()}`);
  console.log(`Product display name: ${product.displayName}`);
  console.log(`Product description: ${product.description}`);
  console.log(`Product category: ${product.productCategory}`);
  console.log(`Product labels: ${product.productLabels}`);
}
getProduct();

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;

/**
 * Get information about a product
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productId ID of the product
 */
function product_get($projectId, $location, $productId)
{
    $client = new ProductSearchClient();

    # get the name of the product.
    $productPath = $client->productName($projectId, $location, $productId);

    # get complete detail of the product.
    $product = $client->getProduct($productPath);

    # display the product information.
    $productName = $product->getName();
    $productNameArray = explode('/', $productName);

    printf('Product name: %s' . PHP_EOL, $productName);
    printf('Product id: %s' . PHP_EOL, end($productNameArray));
    printf('Product display name: %s' . PHP_EOL, $product->getDisplayName());
    printf('Product description: %s' . PHP_EOL, $product->getDescription());
    printf('Product category: %s' . PHP_EOL, $product->getProductCategory());
    print('Product labels: ' . PHP_EOL);
    foreach ($product->getProductLabels() as $label) {
        printf('%s : %s' . PHP_EOL, $label->getKey(), $label->getValue());
    }
    $client->close();
}

Python

from google.cloud import vision
from google.protobuf import field_mask_pb2 as field_mask

def get_product(project_id, location, product_id):
    """Get information about a product.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_id: Id of the product.
    """
    client = vision.ProductSearchClient()

    # Get the full path of the product.
    product_path = client.product_path(
        project=project_id, location=location, product=product_id)

    # Get complete detail of the product.
    product = client.get_product(name=product_path)

    # Display the product information.
    print('Product name: {}'.format(product.name))
    print('Product id: {}'.format(product.name.split('/')[-1]))
    print('Product display name: {}'.format(product.display_name))
    print('Product description: {}'.format(product.description))
    print('Product category: {}'.format(product.product_category))
    print('Product labels: {}'.format(product.product_labels))

Ruby

require "google/cloud/vision"

def product_search_get_product project_id = "your-project-id",
                               location   = "us-west1",
                               product_id = "your-product-id"

  client = Google::Cloud::Vision.product_search

  product_path = client.product_path project:  project_id,
                                     location: location,
                                     product:  product_id

  product = client.get_product name: product_path

  puts "Product name: #{product.name}"
  puts "Product display name: #{product.display_name}"
end

Enumera imágenes de referencia

Un producto puede tener múltiples imágenes de referencia asociadas. En el siguiente ejemplo, se describe cómo obtener todas las imágenes de referencia vinculadas a un solo producto.

LÍNEA DE CMD Y REST

Antes de usar cualquiera de los siguientes datos de solicitud, realiza estos reemplazos:

  • project-id: El ID de tu proyecto de GCP
  • location-id: Un identificador de ubicación válido. Los identificadores de ubicación válidos son los siguientes: us-west1, us-east1, europe-west1 y asia-east1
  • product-id: El ID del producto asociado con una imagen de referencia. Este ID se establece de forma aleatoria, o el usuario lo especifica al momento de crear el producto.

Método HTTP y URL:

GET https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id/referenceImages

Para enviar tu solicitud, elige una de estas opciones:

curl

Ejecuta el siguiente comando:

curl -X GET \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id/referenceImages

PowerShell

Ejecuta el siguiente comando:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id/referenceImages" | Select-Object -Expand Content

Si la solicitud se completa de forma correcta, el servidor muestra un código de estado HTTP 200 OK y la respuesta en formato JSON:

Deberías ver un resultado similar al siguiente. La cantidad predeterminada de imágenes que se muestran es de 10 por vez, y se proporciona un nextPageToken si hay más páginas.

La respuesta que aparece a continuación es para un producto con dos imágenes de referencia. Una de estas imágenes tiene un cuadro de límite asociado, mientras que la otra no tiene un polígono de límite.

Si la respuesta contiene un nextPageToken, quiere decir que hay más resultados. Puedes agregas un parámetro pageToken con el valor de nextPageToken (por ejemplo, 1LqhSgZfM_uWKOxvog) para repetir la solicitud:

https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id/referenceImages?pageToken=1LqhSgZfM_uWKOxvog

C#

private static int ListReferenceImagesOfProduct(ListReferenceImagesOptions opts)
{
    var client = ProductSearchClient.Create();
    var request = new ListReferenceImagesRequest
    {
        // Get the full path of the product.
        ParentAsProductName = new ProductName(opts.ProjectID,
                                              opts.ComputeRegion,
                                              opts.ProductID)
    };

    var referenceImages = client.ListReferenceImages(request);
    foreach (var referenceImage in referenceImages)
    {
        var referenceImageID = referenceImage.Name.Split("/").Last();
        Console.WriteLine($"Reference image name: {referenceImage.Name}");
        Console.WriteLine($"Reference image id: {referenceImageID}");
        Console.WriteLine($"Reference image URI: {referenceImage.Uri}");
        Console.WriteLine("Reference image bounding polygons:");
        Console.WriteLine($"\t{referenceImage.BoundingPolys.ToString()}");
    }

    return 0;
}

Go


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"google.golang.org/api/iterator"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

// listReferenceImages lists reference images of a product.
func listReferenceImages(w io.Writer, projectID string, location string, productID string) error {
	ctx := context.Background()
	c, err := vision.NewProductSearchClient(ctx)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %v", err)
	}
	defer c.Close()

	req := &visionpb.ListReferenceImagesRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s/products/%s", projectID, location, productID),
	}

	it := c.ListReferenceImages(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("Next: %v", err)
		}

		fmt.Fprintf(w, "Reference image name: %s\n", resp.Name)
		fmt.Fprintf(w, "Reference image uri: %s\n", resp.Uri)
		fmt.Fprintf(w, "Reference image bounding polygons: %s\n", resp.BoundingPolys)
	}

	return nil
}

Java

/**
 * List all images in a product.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productId - Id of the product.
 * @throws IOException - on I/O errors.
 */
public static void listReferenceImagesOfProduct(
    String projectId, String computeRegion, String productId) throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // Get the full path of the product.
    String formattedParent =
        ProductSearchClient.formatProductName(projectId, computeRegion, productId);
    for (ReferenceImage image : client.listReferenceImages(formattedParent).iterateAll()) {
      // Display the reference image information.
      System.out.println(String.format("Reference image name: %s", image.getName()));
      System.out.println(
          String.format(
              "Reference image id: %s",
              image.getName().substring(image.getName().lastIndexOf('/') + 1)));
      System.out.println(String.format("Reference image uri: %s", image.getUri()));
      System.out.println(
          String.format(
              "Reference image bounding polygons: %s \n",
              image.getBoundingPolysList().toString()));
    }
  }
}

Node.js

const vision = require('@google-cloud/vision');

const client = new vision.ProductSearchClient();

async function listReferenceImage() {
  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'Your Google Cloud project Id';

  // const formattedParent = client.productPath(projectId, location, productId);
  // const location = 'A compute region name';
  // const productId = 'Id of the product';
  const formattedParent = client.productPath(projectId, location, productId);
  const request = {
    parent: formattedParent,
  };

  const [response] = await client.listReferenceImages(request);
  response.forEach(image => {
    console.log(`image.name: ${image.name}`);
    console.log(`image.uri: ${image.uri}`);
  });
}
listReferenceImage();

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;

/**
 * List all images in
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productId ID of the product
 */
function product_image_list($projectId, $location, $productId)
{
    $client = new ProductSearchClient();

    # get the name of the product.
    $productPath = $client->productName($projectId, $location, $productId);

    # list all the reference images available
    $referenceImages = $client->listReferenceImages($productPath);

    foreach ($referenceImages->iterateAllElements() as $referenceImage) {
        $name = $referenceImage->getName();
        $nameArray = explode('/', $name);

        printf('Reference image name: %s' . PHP_EOL, $name);
        printf('Reference image id: %s' . PHP_EOL, end($nameArray));
        printf('Reference image uri: %s' . PHP_EOL, $referenceImage->getUri());
        print('Reference image bounding polygons: ');
        foreach ($referenceImage->getBoundingPolys() as $boundingPoly) {
            foreach ($boundingPoly->getVertices() as $vertex) {
                printf('(%d, %d) ', $vertex->getX(), $vertex->getY());
            }
            print(PHP_EOL);
        }
    }

    $client->close();
}

Python

from google.cloud import vision

def list_reference_images(
        project_id, location, product_id):
    """List all images in a product.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_id: Id of the product.
    """
    client = vision.ProductSearchClient()

    # Get the full path of the product.
    product_path = client.product_path(
        project=project_id, location=location, product=product_id)

    # List all the reference images available in the product.
    reference_images = client.list_reference_images(parent=product_path)

    # Display the reference image information.
    for image in reference_images:
        print('Reference image name: {}'.format(image.name))
        print('Reference image id: {}'.format(image.name.split('/')[-1]))
        print('Reference image uri: {}'.format(image.uri))
        print('Reference image bounding polygons: {}'.format(
            image.bounding_polys))

Ruby

require "google/cloud/vision"

def product_search_list_reference_images project_id = "your-project-id",
                                         location   = "us-west1",
                                         product_id = "your-product-id"

  client = Google::Cloud::Vision.product_search

  product_path = client.product_path project:  project_id,
                                     location: location,
                                     product:  product_id

  puts "Reference images for product #{product_id}:"
  client.list_reference_images(parent: product_path).each do |reference_image|
    puts "\t#{reference_image.name}"
  end
end

Obtén una sola imagen de referencia

También puedes obtener una sola imagen de referencia vinculada a un producto.

LÍNEA DE CMD Y REST

Antes de usar cualquiera de los siguientes datos de solicitud, realiza estos reemplazos:

  • project-id: El ID de tu proyecto de GCP
  • location-id: Un identificador de ubicación válido. Los identificadores de ubicación válidos son los siguientes: us-west1, us-east1, europe-west1 y asia-east1
  • product-id: El ID del producto asociado con una imagen de referencia. Este ID se establece de forma aleatoria, o el usuario lo especifica al momento de crear el producto.
  • image-id: Es el ID del recurso de la imagen de destino.

Método HTTP y URL:

GET https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id/referenceImages/image-id

Para enviar tu solicitud, elige una de estas opciones:

curl

Ejecuta el siguiente comando:

curl -X GET \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id/referenceImages/image-id

PowerShell

Ejecuta el siguiente comando:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id/referenceImages/image-id" | Select-Object -Expand Content

Si la solicitud se completa de forma correcta, el servidor muestra un código de estado HTTP 200 OK y la respuesta en formato JSON:

Deberías ver un resultado similar al siguiente. La imagen de referencia de ejemplo tiene asociados cuadros de límite especificados.

C#

private static int GetReferenceImage(GetReferenceImageOptions opts)
{
    var client = ProductSearchClient.Create();
    var request = new GetReferenceImageRequest
    {
        // Get the full path of the reference image.
        ReferenceImageName = new ReferenceImageName(opts.ProjectID,
                                                    opts.ComputeRegion,
                                                    opts.ProductID,
                                                    opts.ReferenceImageID)
    };

    var referenceImage = client.GetReferenceImage(request);

    var referenceImageID = referenceImage.Name.Split("/").Last();
    Console.WriteLine($"Reference image name: {referenceImage.Name}");
    Console.WriteLine($"Reference image id: {referenceImageID}");
    Console.WriteLine($"Reference image URI: {referenceImage.Uri}");
    Console.WriteLine("Reference image bounding polygons:");
    Console.WriteLine($"\t{referenceImage.BoundingPolys.ToString()}");
    return 0;
}

Go


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

// getReferenceImage gets a reference image.
func getReferenceImage(w io.Writer, projectID string, location string, productID string, referenceImageID string) error {
	ctx := context.Background()
	c, err := vision.NewProductSearchClient(ctx)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %v", err)
	}
	defer c.Close()

	req := &visionpb.GetReferenceImageRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/products/%s/referenceImages/%s", projectID, location, productID, referenceImageID),
	}

	resp, err := c.GetReferenceImage(ctx, req)
	if err != nil {
		return fmt.Errorf("GetReferenceImage: %v", err)
	}

	fmt.Fprintf(w, "Reference image name: %s\n", resp.Name)
	fmt.Fprintf(w, "Reference image uri: %s\n", resp.Uri)
	fmt.Fprintf(w, "Reference image bounding polygons: %s\n", resp.BoundingPolys)

	return nil
}

Java

/**
 * Get info about a reference image.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productId - Id of the product.
 * @param referenceImageId - Id of the image.
 * @throws IOException - on I/O errors.
 */
public static void getReferenceImage(
    String projectId, String computeRegion, String productId, String referenceImageId)
    throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // Get the full path of the reference image.
    String formattedName =
        ImageName.format(projectId, computeRegion, productId, referenceImageId);
    // Get complete detail of the reference image.
    ReferenceImage image = client.getReferenceImage(formattedName);
    // Display the reference image information.
    System.out.println(String.format("Reference image name: %s", image.getName()));
    System.out.println(
        String.format(
            "Reference image id: %s",
            image.getName().substring(image.getName().lastIndexOf('/') + 1)));
    System.out.println(String.format("Reference image uri: %s", image.getUri()));
    System.out.println(
        String.format(
            "Reference image bounding polygons: %s \n", image.getBoundingPolysList().toString()));
  }
}

Node.js

const vision = require('@google-cloud/vision');

const client = new vision.ProductSearchClient();

async function getReferenceImage() {
  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'Your Google Cloud project Id';
  // const location = 'A compute region name';
  // const productId = 'Id of the product';
  // const referenceImageId = 'Id of the reference image';

  const formattedName = client.referenceImagePath(
    projectId,
    location,
    productId,
    referenceImageId
  );

  const request = {
    name: formattedName,
  };

  const response = await client.getReferenceImage(request);
  console.log(`response.name: ${response.name}`);
  console.log(`response.uri: ${response.uri}`);
}
getReferenceImage();

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;

/**
 * Get info about a reference image
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productId ID of the product
 * @param string $referenceImageId ID of the reference image
 */
function product_image_get($projectId, $location, $productId, $referenceImageId)
{
    $client = new ProductSearchClient();

    # get the name of the reference image.
    $referenceImagePath = $client->referenceImageName($projectId, $location, $productId, $referenceImageId);

    # get complete detail of the reference image.
    $referenceImage = $client->getReferenceImage($referenceImagePath);

    # display reference image information
    $name = $referenceImage->getName();
    $nameArray = explode('/', $name);

    printf('Reference image name: %s' . PHP_EOL, $name);
    printf('Reference image id: %s' . PHP_EOL, end($nameArray));
    printf('Reference image uri: %s' . PHP_EOL, $referenceImage->getUri());
    print('Reference image bounding polygons: ');
    foreach ($referenceImage->getBoundingPolys() as $boundingPoly) {
        foreach ($boundingPoly->getVertices() as $vertex) {
            printf('(%d, %d) ', $vertex->getX(), $vertex->getY());
        }
        print(PHP_EOL);
    }

    $client->close();
}

Python

from google.cloud import vision

def get_reference_image(
        project_id, location, product_id, reference_image_id):
    """Get info about a reference image.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_id: Id of the product.
        reference_image_id: Id of the reference image.
    """
    client = vision.ProductSearchClient()

    # Get the full path of the reference image.
    reference_image_path = client.reference_image_path(
        project=project_id, location=location, product=product_id,
        reference_image=reference_image_id)

    # Get complete detail of the reference image.
    image = client.get_reference_image(name=reference_image_path)

    # Display the reference image information.
    print('Reference image name: {}'.format(image.name))
    print('Reference image id: {}'.format(image.name.split('/')[-1]))
    print('Reference image uri: {}'.format(image.uri))
    print('Reference image bounding polygons: {}'.format(image.bounding_polys))

Ruby

require "google/cloud/vision"

def product_search_get_reference_image project_id = "your-project-id",
                                       location   = "us-west1",
                                       product_id = "your-product-id",
                                       image_id   = "your-image-id"

  client = Google::Cloud::Vision.product_search

  reference_image_path = client.reference_image_path project:         project_id,
                                                     location:        location,
                                                     product:         product_id,
                                                     reference_image: image_id

  image = client.get_reference_image name: reference_image_path

  # Display the reference image information.
  puts "Reference image name: #{image.name}"
  puts "Reference image uri: #{image.uri}"
  puts "Reference image uri: #{image.bounding_polys}"
end