リソースの取得と一覧表示

作成した商品セット、商品、参照画像のリソースをいつでもリスト表示および取得できます。

商品セットをリストする

このセクションでは、すべての商品セットをリスト表示する方法を説明します。

リクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
  • LOCATION_ID: 有効なロケーション ID。有効なロケーション ID は us-west1us-east1europe-west1asia-east1 です。

HTTP メソッドと URL:

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

リクエストを送信するには、次のいずれかのオプションを選択します。

curlPowerShell

次のコマンドを実行します。

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

次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

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

次のような JSON レスポンスが返されます。

{
  "productSets": [
    {
      "name": "projects/project-id/locations/location-id/productSets/product-set-id1",
      "displayName": "display-name1",
      "indexTime": "2019-09-04T15:33:43.581861690Z",
      "indexError": {}
    },
    {
      "name": "projects/project-id/locations/location-id/productSets/product-set-id2",
      "displayName": "display-name2",
      "indexTime": "1970-01-01T00:00:00Z",
      "indexError": {}
    },
    {
      "name": "projects/project-id/locations/location-id/productSets/product-set-id3",
      "displayName": "display-name3",
      "indexTime": "2019-12-26T17:03:38.935312842Z",
      "indexError": {}
    },
    {
      "name": "projects/project-id/locations/location-id/productSets/product-set-id4",
      "displayName": "display-name4",
      "indexTime": "2019-09-04T15:33:43.581861690Z",
      "indexError": {}
    },
    {
      "name": "projects/project-id/locations/location-id/productSets/product-set-id5",
      "displayName": "display-name5",
      "indexTime": "1970-01-01T00:00:00Z",
      "indexError": {}
    }
  ]
}

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Go API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"cloud.google.com/go/vision/v2/apiv1/visionpb"
	"google.golang.org/api/iterator"
)

// 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: %w", 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: %w", 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
}

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Java API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

/**
 * 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 = LocationName.format(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()));
    }
  }
}

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Node.js API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

// 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();

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Python API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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(f"Product set name: {product_set.name}")
        print("Product set id: {}".format(product_set.name.split("/")[-1]))
        print(f"Product set display name: {product_set.display_name}")
        print("Product set index time: ")
        print(product_set.index_time)


C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET. 用の Vision API Product Search のリファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の Vision API Product Search リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の Vision API Product Search リファレンス ドキュメントをご覧ください。

単一の商品セットを取得する

使用または変更する 1 つの商品セットを取得できます。

リクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
  • LOCATION_ID: 有効なロケーション ID。有効なロケーション ID は us-west1us-east1europe-west1asia-east1 です。
  • PRODUCT_SET_ID: 操作を実行する商品セットの ID。

HTTP メソッドと URL:

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

リクエストを送信するには、次のいずれかのオプションを選択します。

curlPowerShell

次のコマンドを実行します。

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

次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

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

次のような JSON レスポンスが返されます。

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

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Go API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"cloud.google.com/go/vision/v2/apiv1/visionpb"
)

// 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: %w", 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: %w", 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
}

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Java API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

/**
 * 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 = ProductSetName.format(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()));
  }
}

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Node.js API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

// 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();

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Python API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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(f"Product set name: {product_set.name}")
    print("Product set id: {}".format(product_set.name.split("/")[-1]))
    print(f"Product set display name: {product_set.display_name}")
    print("Product set index time: ")
    print(product_set.index_time)


C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET. 用の Vision API Product Search のリファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の Vision API Product Search リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の Vision API Product Search リファレンス ドキュメントをご覧ください。

商品を一覧表示する

Google Cloud Platform プロジェクトまたは特定の商品セットのすべての商品を表示できます。

プロジェクトのすべての商品を一覧表示する

次の例では、プロジェクト内の商品を一覧表示します。

リクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
  • LOCATION_ID: 有効なロケーション ID。有効なロケーション ID は us-west1us-east1europe-west1asia-east1 です。

HTTP メソッドと URL:

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

リクエストを送信するには、次のいずれかのオプションを選択します。

curlPowerShell

次のコマンドを実行します。

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

次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

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

リクエストが成功すると、サーバーは 200 OK HTTP ステータス コードと JSON 形式のレスポンスを返します。

出力は次のようになります。一度に返される商品数は 10 個までです。複数ページになる場合は、nextPageToken が提供されます。

{
  "products": [
    {
      "name": "projects/project-id/locations/location-id/products/product-id01",
      "displayName": " ",
      "description": "Athletic shorts",
      "productCategory": "apparel-v2",
      "productLabels": [
        {
          "key": "style",
          "value": "womens"
        },
        {
          "key": "color",
          "value": "blue"
        }
      ]
    },
    {
      "name": "projects/project-id/locations/location-id/products/product-id02",
      "displayName": " ",
      "description": "Athletic shorts",
      "productCategory": "apparel-v2",
      "productLabels": [
        {
          "key": "style",
          "value": "womens"
        },
        {
          "key": "color",
          "value": "blue"
        }
      ]
    },
    {
      "name": "projects/project-id/locations/location-id/products/product-id03",
      "displayName": " ",
      "productCategory": "apparel-v2",
      "productLabels": [
        {
          "key": "style",
          "value": "women"
        },
        {
          "key": "category",
          "value": "shoe"
        }
      ]
    },
    {
      "name": "projects/project-id/locations/location-id/products/product-id04",
      "displayName": " ",
      "productCategory": "apparel-v2",
      "productLabels": [
        {
          "key": "style",
          "value": "men"
        },
        {
          "key": "category",
          "value": "shoe"
        }
      ]
    },
    {
      "name": "projects/project-id/locations/location-id/products/product-id05",
      "displayName": " ",
      "productCategory": "apparel-v2",
      "productLabels": [
        {
          "key": "style",
          "value": "women"
        },
        {
          "key": "category",
          "value": "dress"
        }
      ]
    },
    {
      "name": "projects/project-id/locations/location-id/products/product-id06",
      "displayName": " ",
      "productCategory": "apparel-v2",
      "productLabels": [
        {
          "key": "style",
          "value": "women"
        },
        {
          "key": "category",
          "value": "dress"
        }
      ]
    },
    {
      "name": "projects/project-id/locations/location-id/products/product-id07",
      "displayName": " ",
      "productCategory": "apparel-v2",
      "productLabels": [
        {
          "key": "style",
          "value": "women"
        },
        {
          "key": "category",
          "value": "dress"
        }
      ]
    },
    {
      "name": "projects/project-id/locations/location-id/products/product-id08",
      "displayName": " ",
      "productCategory": "apparel-v2",
      "productLabels": [
        {
          "key": "style",
          "value": "women"
        },
        {
          "key": "category",
          "value": "dress"
        }
      ]
    },
    {
      "name": "projects/project-id/locations/location-id/products/product-id09",
      "displayName": " ",
      "productCategory": "apparel-v2",
      "productLabels": [
        {
          "key": "style",
          "value": "women"
        },
        {
          "key": "category",
          "value": "dress"
        }
      ]
    },
    {
      "name": "projects/project-id/locations/location-id/products/product-id10",
      "displayName": " ",
      "productCategory": "apparel-v2",
      "productLabels": [
        {
          "key": "style",
          "value": "women"
        },
        {
          "key": "category",
          "value": "shoe"
        }
      ]
    }
  ],
  "nextPageToken": "jMGjEqhXMtN95vZz2g"
}

nextPageToken が返された場合は、トークンを使用して商品の次のページを取得できます。リクエスト URL に追加する pageToken クエリとして、レスポンスの JSON にある nextPageToken(この例では jMGjEqhXMtN95vZz2g)を使用します。

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

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Go API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"cloud.google.com/go/vision/v2/apiv1/visionpb"
	"google.golang.org/api/iterator"
)

// 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: %w", 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: %w", 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
}

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Java API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

/**
 * 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 = LocationName.format(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()));
    }
  }
}

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Node.js API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

// 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();

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Python API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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(f"Product name: {product.name}")
        print("Product id: {}".format(product.name.split("/")[-1]))
        print(f"Product display name: {product.display_name}")
        print(f"Product description: {product.description}")
        print(f"Product category: {product.product_category}")
        print(f"Product labels: {product.product_labels}\n")


C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET. 用の Vision API Product Search のリファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の Vision API Product Search リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の Vision API Product Search リファレンス ドキュメントをご覧ください。

商品セット内のすべての商品を一覧表示する

次の例では、特定の商品セットの商品を一覧表示します。

リクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
  • LOCATION_ID: 有効なロケーション ID。有効なロケーション ID は us-west1us-east1europe-west1asia-east1 です。
  • PRODUCT_SET_ID: 操作を実行する商品セットの ID。

HTTP メソッドと URL:

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

リクエストを送信するには、次のいずれかのオプションを選択します。

curlPowerShell

次のコマンドを実行します。

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

次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

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

リクエストが成功すると、サーバーは 200 OK HTTP ステータス コードと JSON 形式のレスポンスを返します。

出力は次のようになります。一度に返される商品数は 10 個までです。複数ページになる場合は、nextPageToken が提供されます。

{
  "products": [
    {
      "name": "projects/project-id/locations/location-id/products/product-id01",
      "displayName": " ",
      "description": "Athletic shorts",
      "productCategory": "apparel-v2",
      "productLabels": [
        {
          "key": "style",
          "value": "womens"
        },
        {
          "key": "color",
          "value": "blue"
        }
      ]
    },
    {
      "name": "projects/project-id/locations/location-id/products/product-id02",
      "displayName": " ",
      "description": "Athletic shorts",
      "productCategory": "apparel-v2",
      "productLabels": [
        {
          "key": "style",
          "value": "womens"
        },
        {
          "key": "color",
          "value": "blue"
        }
      ]
    },
    {
      "name": "projects/project-id/locations/location-id/products/product-id03",
      "displayName": " ",
      "productCategory": "apparel-v2",
      "productLabels": [
        {
          "key": "style",
          "value": "women"
        },
        {
          "key": "category",
          "value": "shoe"
        }
      ]
    },
    {
      "name": "projects/project-id/locations/location-id/products/product-id04",
      "displayName": " ",
      "productCategory": "apparel-v2",
      "productLabels": [
        {
          "key": "style",
          "value": "men"
        },
        {
          "key": "category",
          "value": "shoe"
        }
      ]
    },
    {
      "name": "projects/project-id/locations/location-id/products/product-id05",
      "displayName": " ",
      "productCategory": "apparel-v2",
      "productLabels": [
        {
          "key": "style",
          "value": "women"
        },
        {
          "key": "category",
          "value": "dress"
        }
      ]
    },
    {
      "name": "projects/project-id/locations/location-id/products/product-id06",
      "displayName": " ",
      "productCategory": "apparel-v2",
      "productLabels": [
        {
          "key": "style",
          "value": "women"
        },
        {
          "key": "category",
          "value": "dress"
        }
      ]
    },
    {
      "name": "projects/project-id/locations/location-id/products/product-id07",
      "displayName": " ",
      "productCategory": "apparel-v2",
      "productLabels": [
        {
          "key": "style",
          "value": "women"
        },
        {
          "key": "category",
          "value": "dress"
        }
      ]
    },
    {
      "name": "projects/project-id/locations/location-id/products/product-id08",
      "displayName": " ",
      "productCategory": "apparel-v2",
      "productLabels": [
        {
          "key": "style",
          "value": "women"
        },
        {
          "key": "category",
          "value": "dress"
        }
      ]
    },
    {
      "name": "projects/project-id/locations/location-id/products/product-id09",
      "displayName": " ",
      "productCategory": "apparel-v2",
      "productLabels": [
        {
          "key": "style",
          "value": "women"
        },
        {
          "key": "category",
          "value": "dress"
        }
      ]
    },
    {
      "name": "projects/project-id/locations/location-id/products/product-id10",
      "displayName": " ",
      "productCategory": "apparel-v2",
      "productLabels": [
        {
          "key": "style",
          "value": "women"
        },
        {
          "key": "category",
          "value": "shoe"
        }
      ]
    }
  ],
  "nextPageToken": "e5nEGpoVEZqlBbZRhQ"
}

nextPageToken が返された場合は、トークンを使用して商品の次のページを取得できます。リクエスト URL に追加する pageToken クエリとして、レスポンスの JSON にある nextPageToken(この例では e5nEGpoVEZqlBbZRhQ)を使用します。

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

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Go API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"cloud.google.com/go/vision/v2/apiv1/visionpb"
	"google.golang.org/api/iterator"
)

// 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: %w", 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: %w", 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
}

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Java API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


/**
 * 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 = ProductSetName.format(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()));
      }
    }
  }
}

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Node.js API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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();

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Python API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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(f"Product name: {product.name}")
        print("Product id: {}".format(product.name.split("/")[-1]))
        print(f"Product display name: {product.display_name}")
        print(f"Product description: {product.description}")
        print(f"Product category: {product.product_category}")
        print(f"Product labels: {product.product_labels}")


C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET. 用の Vision API Product Search のリファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の Vision API Product Search リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の Vision API Product Search リファレンス ドキュメントをご覧ください。

単一の商品を取得する

使用または変更する 1 つの商品を取得することもできます。

リクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
  • LOCATION_ID: 有効なロケーション ID。有効なロケーション ID は us-west1us-east1europe-west1asia-east1 です。
  • PRODUCT_ID: 参照画像に関連付けられている商品の ID。この ID は、商品の作成時にユーザーによってランダムに設定または指定されます。

HTTP メソッドと URL:

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

リクエストを送信するには、次のいずれかのオプションを選択します。

curlPowerShell

次のコマンドを実行します。

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

次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

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

次のような JSON レスポンスが返されます。

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

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Go API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"cloud.google.com/go/vision/v2/apiv1/visionpb"
)

// 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: %w", 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: %w", 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
}

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Java API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

/**
 * 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 = ProductName.format(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()));
    }
  }
}

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Node.js API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

// 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();

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Python API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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(f"Product name: {product.name}")
    print("Product id: {}".format(product.name.split("/")[-1]))
    print(f"Product display name: {product.display_name}")
    print(f"Product description: {product.description}")
    print(f"Product category: {product.product_category}")
    print(f"Product labels: {product.product_labels}")


C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET. 用の Vision API Product Search のリファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の Vision API Product Search リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の Vision API Product Search リファレンス ドキュメントをご覧ください。

参照画像を一覧表示する

1 つの商品に複数の参照画像を関連付けることができます。次の例は、単一の商品にリンクされているすべての参照画像を取得する方法を示しています。

リクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
  • LOCATION_ID: 有効なロケーション ID。有効なロケーション ID は us-west1us-east1europe-west1asia-east1 です。
  • PRODUCT_ID: 参照画像に関連付けられている商品の ID。この ID は、商品の作成時にユーザーによってランダムに設定または指定されます。

HTTP メソッドと URL:

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

リクエストを送信するには、次のいずれかのオプションを選択します。

curlPowerShell

次のコマンドを実行します。

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

次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

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

リクエストが成功すると、サーバーは 200 OK HTTP ステータス コードと JSON 形式のレスポンスを返します。

出力は次のようになります。デフォルトでは、一度に返される商品数は 10 個までです。複数ページになる場合は、nextPageToken が提供されます。

以下のレスポンスは、2 つの参照画像がある商品に対するものです。この画像の 1 つには境界ボックスが関連付けられていますが、もう 1 つの画像には境界ポリゴンがありません。

{
  "referenceImages": [
    {
      "name": "projects/project-id/locations/location-id/products/product-id/referenceImages/image-id1",
      "uri": "gs://storage-bucket/filename1.jpg",
      "boundingPolys": [
        {
          "normalizedVertices": [
            {
              "x": 0.10443038,
              "y": 0.06962025
            },
            {
              "x": 0.8924051,
              "y": 0.06962025
            },
            {
              "x": 0.8924051,
              "y": 0.87974685
            },
            {
              "x": 0.10443038,
              "y": 0.87974685
            }
          ]
        }
      ]
    },
    {
      "name": "projects/project-id/locations/location-id/products/product-id/referenceImages/image-id2",
      "uri": "gs://storage-bucket/filename2.jpg"
    }
  ]
}

レスポンスに nextPageToken が含まれている場合は、さらに多くの結果が存在します。pageToken パラメータを追加して nextPageToken の値(たとえば 1LqhSgZfM_uWKOxvog)を指定すると、リクエストを繰り返すことができます。

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

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Go API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"cloud.google.com/go/vision/v2/apiv1/visionpb"
	"google.golang.org/api/iterator"
)

// 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: %w", 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: %w", 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
}

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Java API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

/**
 * 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 = ProductName.format(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()));
    }
  }
}

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Node.js API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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();

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Python API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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(f"Reference image name: {image.name}")
        print("Reference image id: {}".format(image.name.split("/")[-1]))
        print(f"Reference image uri: {image.uri}")
        print("Reference image bounding polygons: {}".format(image.bounding_polys))


C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET. 用の Vision API Product Search のリファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の Vision API Product Search リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の Vision API Product Search リファレンス ドキュメントをご覧ください。

単一の参照画像を取得する

商品にリンクされている 1 つの参照画像を取得することもできます。

リクエストのデータを使用する前に、次のように置き換えます。

  • PROJECT_ID: 実際の Google Cloud プロジェクト ID。
  • LOCATION_ID: 有効なロケーション ID。有効なロケーション ID は us-west1us-east1europe-west1asia-east1 です。
  • PRODUCT_ID: 参照画像に関連付けられている商品の ID。この ID は、商品の作成時にユーザーによってランダムに設定または指定されます。
  • IMAGE_ID: 対象の画像リソースの ID。

HTTP メソッドと URL:

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

リクエストを送信するには、次のいずれかのオプションを選択します。

curlPowerShell

次のコマンドを実行します。

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

次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

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

リクエストが成功すると、サーバーは 200 OK HTTP ステータス コードと JSON 形式のレスポンスを返します。

出力は次のようになります。サンプルの参照画像には、関連する境界ボックスが指定されています。

{
  "name": "projects/project-id/locations/location-id/products/product-id/referenceImages/image-id",
  "uri": "gs://storage-bucket/filename.jpg",
  "boundingPolys": [
    {
      "normalizedVertices": [
        {
          "x": 0.10443038,
          "y": 0.06962025
        },
        {
          "x": 0.8924051,
          "y": 0.06962025
        },
        {
          "x": 0.8924051,
          "y": 0.87974685
        },
        {
          "x": 0.10443038,
          "y": 0.87974685
        }
      ]
    }
  ]
}

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Go API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"cloud.google.com/go/vision/v2/apiv1/visionpb"
)

// 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: %w", 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: %w", 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
}

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Java API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

/**
 * 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()));
  }
}

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Node.js API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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();

Vision API Product Search 用のクライアント ライブラリをインストールして使用する方法については、Vision API Product Search クライアント ライブラリをご覧ください。 詳細については、Vision API Product Search Python API リファレンス ドキュメントをご覧ください。

Vision API Product Search に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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(f"Reference image name: {image.name}")
    print("Reference image id: {}".format(image.name.split("/")[-1]))
    print(f"Reference image uri: {image.uri}")
    print(f"Reference image bounding polygons: {image.bounding_polys}")


C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET. 用の Vision API Product Search のリファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の Vision API Product Search リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の Vision API Product Search リファレンス ドキュメントをご覧ください。