参照画像の作成とインデックス処理

参照画像は、商品のさまざまなビューを含む画像です。次の推奨事項が適用されます。

  • ファイルの大きさが最大サイズ(20 MB)を超えないようにしてください。
  • 商品を論理的に強調して、関連するビジュアル情報が含まれるような視点を考慮してください。
  • 欠けている視点を補うような参照画像を作成します。たとえば、右足の靴の画像しかない場合は、その画像ファイルの鏡像バージョンを左足の靴として提供します。
  • 解像度の最も高い画像をアップロードします。
  • 商品の背景を白にします。
  • 背景が透明の PNG は単色の背景に変換します。

画像は、Cloud Storage バケットに保存する必要があります。API キーを使用して画像作成呼び出しを認証する場合は、バケットが公開されている必要があります。サービス アカウントを使用して認証する場合は、そのサービス アカウントにバケットの読み取りアクセス権が必要です。

単一の参照画像の作成

既存の商品に参照画像を追加できます。その後、該当する商品を画像で検索できるようになります。

REST

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

  • PROJECT_ID: Google Cloud プロジェクト ID。
  • LOCATION_ID: 有効なロケーション ID。有効なロケーション ID は us-west1us-east1europe-west1asia-east1 です。
  • PRODUCT_ID: 参照画像に関連付けられている商品の ID。この ID は、商品の作成時にユーザーによってランダムに設定または指定されます。
  • CLOUD_STORAGE_IMAGE_URI: Cloud Storage バケット内の有効な画像ファイルへのパス。少なくとも、ファイルに対する読み取り権限が必要です。例:
    • gs://storage-bucket/filename.jpg

HTTP メソッドと URL:

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

リクエストの本文(JSON):

{
  "uri": "cloud-storage-image-uri",
  "boundingPolys": [
    {
      "vertices": [
        {
          "x": X_MIN,
          "y": Y_MIN
        },
        {
          "x": X_MAX,
          "y": Y_MIN
        },
        {
          "x": X_MAX,
          "y": Y_MAX
        },
        {
          "x": X_MIN,
          "y": Y_MAX
        }
      ]
    }
  ]
}

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

curl

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id/referenceImages"

PowerShell

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id/referenceImages" | Select-Object -Expand Content

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

出力は次のようになります。このリクエストの例では、画像内の 1 つの boundingPoly が指定されています。境界ボックスの頂点は正規化されません。頂点の値は実際のピクセル値になります。オリジナル画像に合わせて 0 から 1 の範囲でスケーリングされません。これらの頂点の値は [(33,22),(282,22),(282,278),(33,278)] になります。


{
  "name": "projects/project-id/locations/location-id/products/product-id/referenceImages/image-id",
  "uri": "gs://storage-bucket/filename.jpg",
  "boundingPolys": [
    {
      "vertices": [
        {
          "x": 33,
          "y": 22
        },
        {
          "x": 282,
          "y": 22
        },
        {
          "x": 282,
          "y": 278
        },
        {
          "x": 33,
          "y": 278
        }
      ]
    }
  ]
}

Go

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"
)

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

	req := &visionpb.CreateReferenceImageRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s/products/%s", projectID, location, productID),
		ReferenceImage: &visionpb.ReferenceImage{
			Uri: gcsURI,
		},
		ReferenceImageId: referenceImageID,
	}

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

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

	return nil
}

Java

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

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

/**
 * Create 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.
 * @param gcsUri - Google Cloud Storage path of the input image.
 * @throws IOException - on I/O errors.
 */
public static void createReferenceImage(
    String projectId,
    String computeRegion,
    String productId,
    String referenceImageId,
    String gcsUri)
    throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // Get the full path of the product.
    String formattedParent = ProductName.format(projectId, computeRegion, productId);
    // Create a reference image.
    ReferenceImage referenceImage = ReferenceImage.newBuilder().setUri(gcsUri).build();

    ReferenceImage image =
        client.createReferenceImage(formattedParent, referenceImage, referenceImageId);
    // Display the reference image information.
    System.out.println(String.format("Reference image name: %s", image.getName()));
    System.out.println(String.format("Reference image uri: %s", image.getUri()));
  }
}

Node.js

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 createReferenceImage() {
  /**
   * 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 gcsUri = 'Google Cloud Storage path of the input image';

  const formattedParent = client.productPath(projectId, location, productId);

  const referenceImage = {
    uri: gcsUri,
  };

  const request = {
    parent: formattedParent,
    referenceImage: referenceImage,
    referenceImageId: referenceImageId,
  };

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

Python

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

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

from google.cloud import vision

def create_reference_image(
    project_id, location, product_id, reference_image_id, gcs_uri
):
    """Create 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.
        gcs_uri: Google Cloud Storage path of the input image.
    """
    client = vision.ProductSearchClient()

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

    # Create a reference image.
    reference_image = vision.ReferenceImage(uri=gcs_uri)

    # The response is the reference image with `name` populated.
    image = client.create_reference_image(
        parent=product_path,
        reference_image=reference_image,
        reference_image_id=reference_image_id,
    )

    # Display the reference image information.
    print(f"Reference image name: {image.name}")
    print(f"Reference image uri: {image.uri}")

その他の言語

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

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

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

一括インポートで複数の参照画像を作成する

商品セットと複数の商品を作成するときに参照画像も作成できます。

参照画像を一括で作成するには、CSV ファイルが存在する Cloud Storage 上の場所を import メソッドに渡します。CSV ファイルとそれが参照する画像の両方が Cloud Storage バケットに存在している必要があります。

API キーで一括インポート呼び出しの認証を行う場合、この CSV ソースファイルを一般公開にする必要があります。

サービス アカウントで認証を行う場合は、そのサービス アカウントに CSV ソースファイルに対する読み取りアクセス権が必要です。

CSV 形式

image-uri,[image-id],product-set-id,product-id,product-category,[product-display-name],[label(s)],[bounding-poly]

CSV 形式の詳細については、入門トピックの CSV 形式をご覧ください。

一括作成リクエスト

REST

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

  • PROJECT_ID: Google Cloud プロジェクト ID。
  • LOCATION_ID: 有効なロケーション ID。有効なロケーション ID は us-west1us-east1europe-west1asia-east1 です。
  • STORAGE_PATH: 入力 CSV ファイルが保存される Cloud Storage バケット / ディレクトリ。リクエスト元のユーザーには、少なくともバケットに対する読み取り権限が必要です。

HTTP メソッドと URL:

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

リクエストの本文(JSON):

{
  "inputConfig": {
    "gcsSource": {
      "csvFileUri": "storage-path"
    }
  }
}

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

curl

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets:import"

PowerShell

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets:import" | Select-Object -Expand Content

出力は次のようになります。タスクのステータスは、オペレーション ID(この場合は f10f34e32c40a710)を使用して取得できます。例については、オペレーションのステータスの取得をご覧ください。

{
  "name": "projects/project-id/locations/location-id/operations/f10f34e32c40a710"
}

長時間実行オペレーションが完了すると、インポートのオペレーションの詳細を取得できます。レスポンスは次のようになります。

{
  "name": "locations/location-id/operations/f10f34e32c40a710",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.BatchOperationMetadata",
    "state": "SUCCESSFUL",
    "submitTime": "2019-12-06T21:16:04.476466873Z",
    "endTime": "2019-12-06T21:16:40.594258084Z"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.ImportProductSetsResponse",
    "referenceImages": [
      {
        "name": "projects/project-id/locations/location-id/products/product_id0/referenceImages/image0",
        "uri": "gs://my-storage-bucket/img_039.jpg"
      },
      {
        "name": "projects/project-id/locations/location-id/products/product_id1/referenceImages/image1",
        "uri": "gs://my-storage-bucket/img_105.jpg"
      },
      {
        "name": "projects/project-id/locations/location-id/products/product_id2/referenceImages/image2",
        "uri": "gs://my-storage-bucket/img_224.jpg"
      },
      {
        "name": "projects/project-id/locations/location-id/products/product_id3/referenceImages/image3",
        "uri": "gs://my-storage-bucket/img_385.jpg"
      }
    ],
    "statuses": [
      {},
      {},
      {},
      {}
    ]
  }
}

Go

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"
)

// importProductSets creates a product set using information in a csv file on GCS.
func importProductSets(w io.Writer, projectID string, location string, gcsURI string) error {
	ctx := context.Background()
	c, err := vision.NewProductSearchClient(ctx)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %w", err)
	}
	defer c.Close()

	req := &visionpb.ImportProductSetsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		InputConfig: &visionpb.ImportProductSetsInputConfig{
			Source: &visionpb.ImportProductSetsInputConfig_GcsSource{
				GcsSource: &visionpb.ImportProductSetsGcsSource{
					CsvFileUri: gcsURI,
				},
			},
		},
	}

	op, err := c.ImportProductSets(ctx, req)
	if err != nil {
		return fmt.Errorf("ImportProductSets: %w", err)
	}

	fmt.Fprintf(w, "Processing operation name: %s\n", op.Name())

	resp, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

	fmt.Fprintf(w, "processing done.\n")

	for i, status := range resp.Statuses {
		// `0` is the coee for OK in google.rpc.code
		fmt.Fprintf(w, "Status of processing line %d of the csv: %d\n", i, status.Code)

		if status.Code == 0 {
			fmt.Fprintf(w, "Reference image name: %s\n", resp.ReferenceImages[i].Name)
		} else {
			fmt.Fprintf(w, "Status code not OK: %s\n", status.Message)
		}
	}

	return nil
}

Java

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

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

/**
 * Import images of different products in the product set.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param gcsUri - Google Cloud Storage URI.Target files must be in Product Search CSV format.
 * @throws Exception - on client errors.
 */
public static void importProductSets(String projectId, String computeRegion, String gcsUri)
    throws Exception {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // A resource that represents Google Cloud Platform location.
    String formattedParent = LocationName.format(projectId, computeRegion);
    Builder gcsSource = ImportProductSetsGcsSource.newBuilder().setCsvFileUri(gcsUri);

    // Set the input configuration along with Google Cloud Storage URI
    ImportProductSetsInputConfig inputConfig =
        ImportProductSetsInputConfig.newBuilder().setGcsSource(gcsSource).build();

    // Import the product sets from the input URI.
    OperationFuture<ImportProductSetsResponse, BatchOperationMetadata> response =
        client.importProductSetsAsync(formattedParent, inputConfig);

    System.out.println(String.format("Processing operation name: %s", response.getName()));
    ImportProductSetsResponse results = response.get();
    System.out.println("Processing done.");
    System.out.println("Results of the processing:");

    for (int i = 0; i < results.getStatusesCount(); i++) {
      System.out.println(
          String.format(
              "Status of processing line %s of the csv: %s", i, results.getStatuses(i)));
      // Check the status of reference image.
      if (results.getStatuses(i).getCode() == 0) {
        ReferenceImage referenceImage = results.getReferenceImages(i);
        System.out.println(referenceImage);
      } else {
        System.out.println("No reference image.");
      }
    }
  }
}

Node.js

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 importProductSets() {
  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'Your Google Cloud project Id';
  // const location = 'A compute region name';
  // const gcsUri = 'Google Cloud Storage URI. Target files must be in Product Search CSV format';

  // A resource that represents Google Cloud Platform location.
  const projectLocation = client.locationPath(projectId, location);

  // Set the input configuration along with Google Cloud Storage URI
  const inputConfig = {
    gcsSource: {
      csvFileUri: gcsUri,
    },
  };

  // Import the product sets from the input URI.
  const [response, operation] = await client.importProductSets({
    parent: projectLocation,
    inputConfig: inputConfig,
  });

  console.log('Processing operation name: ', operation.name);

  // synchronous check of operation status
  const [result] = await response.promise();
  console.log('Processing done.');
  console.log('Results of the processing:');

  for (const i in result.statuses) {
    console.log(
      'Status of processing ',
      i,
      'of the csv:',
      result.statuses[i]
    );

    // Check the status of reference image
    if (result.statuses[i].code === 0) {
      console.log(result.referenceImages[i]);
    } else {
      console.log('No reference image.');
    }
  }
}
importProductSets();

Python

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

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

def import_product_sets(project_id, location, gcs_uri):
    """Import images of different products in the product set.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        gcs_uri: Google Cloud Storage URI.
            Target files must be in Product Search CSV format.
    """
    client = vision.ProductSearchClient()

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

    # Set the input configuration along with Google Cloud Storage URI
    gcs_source = vision.ImportProductSetsGcsSource(csv_file_uri=gcs_uri)
    input_config = vision.ImportProductSetsInputConfig(gcs_source=gcs_source)

    # Import the product sets from the input URI.
    response = client.import_product_sets(
        parent=location_path, input_config=input_config
    )

    print(f"Processing operation name: {response.operation.name}")
    # synchronous check of operation status
    result = response.result()
    print("Processing done.")

    for i, status in enumerate(result.statuses):
        print("Status of processing line {} of the csv: {}".format(i, status))
        # Check the status of reference image
        # `0` is the code for OK in google.rpc.Code.
        if status.code == 0:
            reference_image = result.reference_images[i]
            print(reference_image)
        else:
            print(f"Status code not OK: {status.message}")

その他の言語

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

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

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

インデックス登録

商品の Product Search インデックスは、約 30 分ごとに更新されます。画像が追加または削除されると、その変更はインデックスが次に更新されるまで Product Search のレスポンスに反映されません。

インデックス登録が正常に完了したことを確認するには、商品セットの indexTime フィールドを確認します。