创建参考图片并将其编入索引

参考图片是包含商品各种视图的图片。请采用下列建议:

  • 确保文件大小不超过上限 (20MB)。
  • 考虑逻辑上突出显示商品并包含相关视觉信息的视角。
  • 创建可以补充缺失视角的参考图片。例如,如果您只有一些右脚鞋子的图片,请提供这些文件的镜像版本作为左角鞋子。
  • 上传分辨率最高的可用图片。
  • 以白色为背景显示商品。
  • 将具有透明背景的 PNG 格式图片转换为纯色背景。

图片必须存储在 Cloud Storage 存储桶中。如果您使用 API 密钥对图片创建调用进行身份验证,则该存储桶必须是公开的。如果您使用服务账号进行身份验证,则该服务账号必须对此存储桶具有读取权限。

创建单张参考图片

您可以为现有商品添加参考图片。这样就可以按图片搜索商品。

REST

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目 ID。
  • LOCATION_ID:有效的位置标识符。有效的位置标识符包括 us-west1us-east1europe-west1asia-east1
  • PRODUCT_ID:与参考图片关联的商品的 ID。此 ID 由用户在创建商品时随机设置或指定。
  • CLOUD_STORAGE_IMAGE_URI:Cloud Storage 存储桶中有效图片文件的路径。您必须至少拥有该文件的读取权限。 示例:
    • gs://storage-bucket/filename.jpg

HTTP 方法和网址:

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 格式的响应。

您应该会看到类似如下所示的输出。示例请求在图片中指定了单个 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:有效的位置标识符。有效的位置标识符包括 us-west1us-east1europe-west1asia-east1
  • STORAGE_PATH:存储输入 CSV 文件的 Cloud Storage 存储桶/目录。发出请求的用户必须至少具有相应存储桶的读取权限。

HTTP 方法和网址:

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 字段。