상품검색 가이드

이 가이드에서는 상품의 참조 이미지가 있는 상품 그룹을 포함하는 상품 세트를 만드는 방법을 설명합니다. 이 가이드는 사용자에게 온라인 (개별) 가져오기를 통해 상품 세트를 만드는 방법을 보여줍니다. 제품 세트의 색인이 생성된 후에는 Vision 제품 검색을 사용하여 제품 세트를 쿼리할 수 있습니다.

이 가이드에서는 다음과 같은 방법을 알아봅니다.

  1. 온라인 (개별) 가져오기를 통해 상품 세트 만들기
  2. 개별 상품 만들기
  3. 상품 세트에 상품 추가
  4. 상품 업데이트
  5. 참조 이미지 만들기
  6. 유사한 상품 검색

시작하기 전에

이 가이드를 시작하기 전에 적절한 클라이언트 라이브러리를 설치하고, 프로젝트에 대하여 청구 및 API를 사용 설정하고, 올바르게 인증을 설정했는지 확인하세요.

라이브러리 가져오기

Cloud Vision 제품 검색을 사용하려면 클라이언트 라이브러리를 다운로드하여 설치한 후에 다음 모듈을 가져오세요.

C#

using Google.Cloud.Vision.V1;

Go


import (
	"context"
	"fmt"
	"io"

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

자바

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.vision.v1.BatchOperationMetadata;
import com.google.cloud.vision.v1.ImportProductSetsGcsSource;
import com.google.cloud.vision.v1.ImportProductSetsGcsSource.Builder;
import com.google.cloud.vision.v1.ImportProductSetsInputConfig;
import com.google.cloud.vision.v1.ImportProductSetsResponse;
import com.google.cloud.vision.v1.ProductSearchClient;
import com.google.cloud.vision.v1.ReferenceImage;

Node.js

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

PHP

use Google\Cloud\Vision\V1\ProductSearchClient;
use Google\Cloud\Vision\V1\ImportProductSetsGcsSource;
use Google\Cloud\Vision\V1\ImportProductSetsInputConfig;

Python

from google.cloud import vision

Ruby

require "google/cloud/vision"

애플리케이션 실행

1단계: 상품 카탈로그 만들기

사용자는 두 가지 방법으로 상품 카탈로그를 만들 수 있습니다. 하나는 CSV 파일을 사용하는 일괄 가져오기를 통한 방법으로, 전체 상품 카탈로그를 단일 API 호출로 가져올 수 있습니다. 다른 하나는 온라인 가져오기를 통한 방법으로, 상품 세트에 대한 제어 기능을 제공하며 리소스 또는 관계를 한 번에 하나씩 관리할 수 있습니다. 이 경우 주로 상품 세트, 상품, 참조 이미지가 개별적으로 만들어집니다. 또한 온라인 가져오기를 이용하면 일괄 가져오기를 통해 이미 만든 제품 카탈로그를 증분 방식으로 업데이트할 수 있습니다.

이 가이드에서는 온라인 가져오기를 사용합니다. CSV를 사용하는 일괄 가져오기의 예는 빠른 시작을 참조하세요.

온라인 (개별) 가져오기

1. 상품 세트 만들기

상품 그룹의 단순한 컨테이너인 빈 상품 세트를 만듭니다.

요청

빈 제품 세트를 만들고 create_product_set() 메서드를 사용하여 다음 요청을 실행하여 이름을 'PS_CLOTH-SHOE_070318'로 지정합니다. 제품 세트 ID와 표시 이름을 인수로 전달하세요.

REST 및 명령줄

아래의 요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: GCP 프로젝트 ID입니다.
  • location-id: 유효한 위치 식별자입니다. 유효한 위치 식별자는 us-west1, us-east1, europe-west1, asia-east1입니다.
  • display-name: 선택한 문자열 표시 이름입니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
  "displayName": "display-name"
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

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" | Select-Object -Expand Content

요청이 성공하면 서버가 200 OK HTTP 상태 코드와 응답을 JSON 형식으로 반환합니다.

다음과 비슷한 출력이 표시됩니다. 제품 세트 ID(이 경우 b6d809615b6dd675)를 사용하여 제품 세트의 다른 작업을 수행할 수 있습니다.

{
  "name": "projects/project-id/locations/location-id/productSets/b6d809615b6dd675",
  "displayName": "new-product-set"
}

C#

        private static object CreateProductSet(CreateProductSetsOptions opts)
        {
            var client = ProductSearchClient.Create();

            // Create a product set with the product set specification in the region.
            var request = new CreateProductSetRequest
            {
                // A resource that represents Google Cloud Platform location
                ParentAsLocationName = new LocationName(opts.ProjectID,
                                                        opts.ComputeRegion),
                ProductSetId = opts.ProductSetId,
                ProductSet = new ProductSet
                {
                    DisplayName = opts.ProductSetDisplayName
                }
            };

            // The response is the product set with the `name` populated
            var response = client.CreateProductSet(request);

            Console.WriteLine($"Product set name: {response.DisplayName}");

            return 0;
        }

Go


import (
	"context"
	"fmt"
	"io"

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

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

	req := &visionpb.CreateProductSetRequest{
		Parent:       fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		ProductSetId: productSetID,
		ProductSet: &visionpb.ProductSet{
			DisplayName: productSetDisplayName,
		},
	}

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

	fmt.Fprintf(w, "Product set name: %s\n", resp.Name)

	return nil
}

자바

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

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

    // Create a product set with the product set specification in the region.
    ProductSet myProductSet =
        ProductSet.newBuilder().setDisplayName(productSetDisplayName).build();
    CreateProductSetRequest request =
        CreateProductSetRequest.newBuilder()
            .setParent(formattedParent)
            .setProductSet(myProductSet)
            .setProductSetId(productSetId)
            .build();
    ProductSet productSet = client.createProductSet(request);
    // Display the product set information
    System.out.println(String.format("Product set name: %s", productSet.getName()));
  }
}

Node.js

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

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

  /**
   * 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 productSetDisplayName = 'Display name of the product set';

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

  const productSet = {
    displayName: productSetDisplayName,
  };

  const request = {
    parent: locationPath,
    productSet: productSet,
    productSetId: productSetId,
  };

  const [createdProductSet] = await client.createProductSet(request);
  console.log(`Product Set name: ${createdProductSet.name}`);
}

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;
use Google\Cloud\Vision\V1\ProductSet;

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

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

    # create a product set with the product set specification in the region.
    $productSet = (new ProductSet())
        ->setDisplayName($productSetDisplayName);

    # the response is the product set with the `name` field populated.
    $response = $client->createProductSet($locationPath, $productSet, ['productSetId' => $productSetId]);

    # display the product information.
    printf('Product set name: %s' . PHP_EOL, $response->getName());

    $client->close();
}

Python

from google.cloud import vision

def create_product_set(
        project_id, location, product_set_id, product_set_display_name):
    """Create a product set.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_set_id: Id of the product set.
        product_set_display_name: Display name of the product set.
    """
    client = vision.ProductSearchClient()

    # A resource that represents Google Cloud Platform location.
    location_path = client.location_path(
        project=project_id, location=location)

    # Create a product set with the product set specification in the region.
    product_set = vision.types.ProductSet(
            display_name=product_set_display_name)

    # The response is the product set with `name` populated.
    response = client.create_product_set(
        parent=location_path,
        product_set=product_set,
        product_set_id=product_set_id)

    # Display the product set information.
    print('Product set name: {}'.format(response.name))

Ruby

require "google/cloud/vision"

def product_search_create_product_set project_id = "your-project-id"
  client = Google::Cloud::Vision.product_search

  # A resource that represents Google Cloud Platform location.
  location = "us-west1" # specify a compute region name
  location_path = client.location_path project: project_id, location: location

  # Create a product set with the product set specification in the region.
  product_set = {
    display_name: "display-name"
  }

  # The response is the product set with `name` populated.
  product_set = client.create_product_set parent:      location_path,
                                          product_set: product_set

  # Display the product set information.
  puts "Product set name: #{product_set.name}"
end

응답

Product set name: projects/prj-prod-search-tutorials/locations/us-east1/productSets/PS_CLOTH-SHOE_070318
Product set id: PS_CLOTH-SHOE_070318
Product set display name: CLOTH-SHOE

2. 상품 만들기

상품 세트가 만들어진 후의 다음 단계는 상품을 만드는 것입니다. 다음 요청을 실행하여 상품을 만듭니다.

REST 및 명령줄

아래의 요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: GCP 프로젝트 ID입니다.
  • location-id: 유효한 위치 식별자입니다. 유효한 위치 식별자는 us-west1, us-east1, europe-west1, asia-east1입니다.
  • display-name: 선택한 문자열 표시 이름입니다.
  • product-description: 선택한 문자열 설명입니다.
  • product-category: 유효한 제품 카테고리입니다. 현재 사용할 수 있는 제품 카테고리는 homegoods-v2, apparel-v2, toys-v2, packagedgoods-v1, general-v1입니다.
  • productLabels: 제품과 연결된 하나 이상의 키-값 쌍입니다. 각 key-string에는 연결된 value-string이 있어야 합니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
  "displayName": "display-name",
  "description": "product-description",
  "productCategory": "product-category",
  "productLabels": [
      {
        "key": "key-string",
        "value": "value-string"
      }
  ]
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

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" | Select-Object -Expand Content

요청 본문 예시:

{
  "displayName": "sample-product-1234",
  "description": "Athletic shorts",
  "productCategory": "apparel-v2",
  "productLabels": [
      {
        "key": "style",
        "value": "womens"
      },
      {
        "key": "color",
        "value": "blue"
      }
  ]
}

요청이 성공하면 서버가 200 OK HTTP 상태 코드와 응답을 JSON 형식으로 반환합니다.

다음과 비슷한 출력이 표시됩니다. 제품 ID(이 경우 37b9811d308c4e42)를 사용하여 제품에 다른 작업을 수행할 수 있습니다.

{
  "name": "projects/project-id/locations/location-id/products/37b9811d308c4e42",
  "displayName": "sample-product-456",
  "description": "Athletic shorts",
  "productCategory": "apparel-v2",
  "productLabels": [
    {
      "key": "style",
      "value": "womens"
    },
    {
      "key": "color",
      "value": "blue"
    }
  ]
}

C#

private static int CreateProduct(CreateProductOptions opts)
{
    var client = ProductSearchClient.Create();
    var request = new CreateProductRequest
    {
        // A resource that represents Google Cloud Platform location.
        ParentAsLocationName = new LocationName(opts.ProjectID,
                                                opts.ComputeRegion),
        // Set product category and product display name
        Product = new Product
        {
            DisplayName = opts.DisplayName,
            ProductCategory = opts.ProductCategory
        },
        ProductId = opts.ProductID
    };

    // The response is the product with the `name` field populated.
    var product = client.CreateProduct(request);

    Console.WriteLine($"Product name: {product.Name}");
    return 0;
}

Go


import (
	"context"
	"fmt"
	"io"

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

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

	req := &visionpb.CreateProductRequest{
		Parent:    fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		ProductId: productID,
		Product: &visionpb.Product{
			DisplayName:     productDisplayName,
			ProductCategory: productCategory,
		},
	}

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

	fmt.Fprintf(w, "Product name: %s\n", resp.Name)

	return nil
}

자바

/**
 * Create one product.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productId - Id of the product.
 * @param productDisplayName - Display name of the product.
 * @param productCategory - Category of the product.
 * @throws IOException - on I/O errors.
 */
public static void createProduct(
    String projectId,
    String computeRegion,
    String productId,
    String productDisplayName,
    String productCategory)
    throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // A resource that represents Google Cloud Platform location.
    String formattedParent = ProductSearchClient.formatLocationName(projectId, computeRegion);
    // Create a product with the product specification in the region.
    // Multiple labels are also supported.
    Product myProduct =
        Product.newBuilder()
            .setName(productId)
            .setDisplayName(productDisplayName)
            .setProductCategory(productCategory)
            .build();
    Product product = client.createProduct(formattedParent, myProduct, productId);
    // Display the product information
    System.out.println(String.format("Product name: %s", product.getName()));
  }
}

Node.js

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

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

  /**
   * 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 productDisplayName = 'Display name of the product';
  // const productCategory = 'Catoegory of the product';

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

  const product = {
    displayName: productDisplayName,
    productCategory: productCategory,
  };

  const request = {
    parent: locationPath,
    product: product,
    productId: productId,
  };

  const [createdProduct] = await client.createProduct(request);
  console.log(`Product name: ${createdProduct.name}`);
}

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;
use Google\Cloud\Vision\V1\Product;

/**
 * Create one product
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productId ID of the product
 * @param string $productDisplayName Display name of the product
 * @param string $productCategory Category of the product
 */
function product_create($projectId, $location, $productId, $productDisplayName, $productCategory)
{
    $client = new ProductSearchClient();

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

    # create a product with the product specification in the region.
    # set product name and product display name.
    $product = (new Product())
        ->setDisplayName($productDisplayName)
        ->setProductCategory($productCategory);

    # the response is the product with the `name` field populated.
    $response = $client->createProduct($locationPath, $product, ['productId' => $productId]);

    # display the product information.
    printf('Product name: %s' . PHP_EOL, $response->getName());

    $client->close();
}

Python

from google.cloud import vision

def create_product(
        project_id, location, product_id, product_display_name,
        product_category):
    """Create one product.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_id: Id of the product.
        product_display_name: Display name of the product.
        product_category: Category of the product.
    """
    client = vision.ProductSearchClient()

    # A resource that represents Google Cloud Platform location.
    location_path = client.location_path(project=project_id, location=location)

    # Create a product with the product specification in the region.
    # Set product display name and product category.
    product = vision.types.Product(
        display_name=product_display_name,
        product_category=product_category)

    # The response is the product with the `name` field populated.
    response = client.create_product(
        parent=location_path,
        product=product,
        product_id=product_id)

    # Display the product information.
    print('Product name: {}'.format(response.name))

Ruby

require "google/cloud/vision"

def product_search_create_product project_id = "your-project-id"
  client = Google::Cloud::Vision.product_search

  # A resource that represents Google Cloud Platform location.
  location      = "us-west1" # specify a compute region name
  location_path = client.location_path project: project_id, location: location

  # Create a product with the product specification in the region.
  # Set product display name and product category.
  product = {
    display_name:     "sample-product-1234",
    description:      "Athletic shorts",
    product_category: "apparel",
    product_labels:   [{ key: "color", value: "blue" }]
  }

  # The response is the product with the `name` field populated.
  product = client.create_product parent: location_path, product: product

  # Display the product information.
  puts "Product name: #{product.name}"
end

응답

Product name: projects/prj-prod-search-tutorials/locations/us-east1/products/P_CLOTH-SHOE_46903668_070318
Product id: P_CLOTH-SHOE_46903668_070318
Product display name: Blue Dress
Product category: apparel
Product description: Short sleeved and 1950s style satin dress
Product labels:
  Product label 1:
        key: style
        value: women
  Product label 2:
        key: category
        value: dress
  Product label 3:
        key: color
        value: dark-blue

3. 상품 세트에 상품 추가

상품 세트와 상품이 만들어진 후에는 상품을 상품 세트에 추가할 수 있습니다.

REST 및 명령줄

아래의 요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: GCP 프로젝트 ID입니다.
  • location-id: 유효한 위치 식별자입니다. 유효한 위치 식별자는 us-west1, us-east1, europe-west1, asia-east1입니다.
  • product-set-id: 작업을 실행할 제품 세트의 ID입니다.
  • product-name: 제품의 전체 리소스 이름입니다. 형식:
    • projects/project-id/locations/location-id/products/product-id

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
  "product": "product-name"
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

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/product-set-id:addProduct" | Select-Object -Expand Content

다음과 비슷한 JSON 응답이 표시됩니다.

{}

C#

private static int AddProductToProductSet(AddProductToProductSetOptions opts)
{
    var client = ProductSearchClient.Create();
    var request = new AddProductToProductSetRequest
    {
        // Get the full path of the products
        ProductAsProductName = new ProductName(opts.ProjectID,
                                              opts.ComputeRegion,
                                              opts.ProductID),
        // Get the full path of the product set.
        ProductSetName = new ProductSetName(opts.ProjectID,
                                           opts.ComputeRegion,
                                           opts.ProductSetId),
    };

    client.AddProductToProductSet(request);

    Console.WriteLine("Product added to product set.");

    return 0;
}

Go


import (
	"context"
	"fmt"
	"io"

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

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

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

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

	fmt.Fprintf(w, "Product added to product set.\n")

	return nil
}

자바

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

    // Get the full path of the product set.
    String formattedName =
        ProductSearchClient.formatProductSetName(projectId, computeRegion, productSetId);

    // Get the full path of the product.
    String productPath = ProductName.of(projectId, computeRegion, productId).toString();

    // Add the product to the product set.
    client.addProductToProductSet(formattedName, productPath);

    System.out.println(String.format("Product added to product set."));
  }
}

Node.js

async function addProductToProductSet() {
  const vision = require('@google-cloud/vision');

  const client = new vision.ProductSearchClient();

  /**
   * 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 productSetId = 'Id of the product set';

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

  const request = {
    name: productSetPath,
    product: productPath,
  };

  await client.addProductToProductSet(request);
  console.log('Product added to product set.');
}

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;

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

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

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

    # add product to product set
    $client->addProductToProductSet($productSetPath, $productPath);
    print('Product added to product set.' . PHP_EOL);

    $client->close();
}

Python

from google.cloud import vision

def add_product_to_product_set(
        project_id, location, product_id, product_set_id):
    """Add a product to a product set.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_id: Id of the product.
        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 the full path of the product.
    product_path = client.product_path(
        project=project_id, location=location, product=product_id)

    # Add the product to the product set.
    client.add_product_to_product_set(
        name=product_set_path, product=product_path)
    print('Product added to product set.')

Ruby

require "google/cloud/vision"

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

  client = Google::Cloud::Vision.product_search

  # 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 the full path of the product.
  product_path = client.product_path project:  project_id,
                                     location: location,
                                     product:  product_id

  # Add the product to the product set.
  client.add_product_to_product_set name:    product_set_path,
                                    product: product_path

  puts "Product #{product_id} added to product set #{product_set_id}."
end

응답

Product added to product set.

4. 상품 업데이트

상품 또는 상품 세트가 만들어진 후에 이를 업데이트해야 하는 경우 update 메소드를 사용할 수 있습니다. 이 예제에서는 라벨이 변경된 경우의 상품 업데이트를 보여줍니다.

명령줄

제품을 업데이트하려면 다음 URI로 PATCH 요청을 보냅니다.
  • project-id를 Google Cloud Platform(GCP) 프로젝트의 ID로 바꿉니다.
  • location-id를 유효한 위치 식별자로 바꿉니다. 유효한 위치 식별자는 us-west1, us-east1, europe-west1, asia-east1입니다.
  • product-id를 업데이트할 제품의 ID로 바꿉니다.
curl -X PATCH \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id -d "{
   'updateMask': { 'paths': ['display_name'] },
   'product': { 'display_name': 'new-display-name' }
}"

C#

private static int UpdateProductLabels(UpdateProductLabelsOptions opts)
{
    var client = ProductSearchClient.Create();
    var request = new UpdateProductRequest
    {
        Product = new Product
        {
            // Get the name of the product
            ProductName = new ProductName(opts.ProjectID,
                                         opts.ComputeRegion,
                                         opts.ProductID),
            // Set the product name, product label, and product display
            // name. Multiple labels are also supported.
            ProductLabels =
            {
                new Product.Types.KeyValue
                {
                    Key = opts.Labels.Split(",").First(),
                    Value = opts.Labels.Split(",").Last()
                }
            }
        },
        // Updating only the product_labels field here.
        UpdateMask = new FieldMask
        {
            Paths = { "product_labels" }
        }
    };

    // This overwrites the product_labels.
    var product = client.UpdateProduct(request);

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

Go


import (
	"context"
	"fmt"
	"io"

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

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

	req := &visionpb.UpdateProductRequest{
		UpdateMask: &field_mask.FieldMask{
			Paths: []string{
				"product_labels",
			},
		},
		Product: &visionpb.Product{
			Name: fmt.Sprintf("projects/%s/locations/%s/products/%s", projectID, location, productID),
			ProductLabels: []*visionpb.Product_KeyValue{
				{
					Key:   key,
					Value: value,
				},
			},
		},
	}

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

	fmt.Fprintf(w, "Product name: %s\n", resp.Name)
	fmt.Fprintf(w, "Updated product labels: %s\n", resp.ProductLabels)

	return nil
}

자바

/**
 * Update the product labels.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productId -Id of the product.
 * @param productLabels - Labels of the product.
 * @throws IOException - on I/O errors.
 */
public static void updateProductLabels(
    String projectId, String computeRegion, String productId, String productLabels)
    throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // Get the full path of the product.
    String formattedName =
        ProductSearchClient.formatProductName(projectId, computeRegion, productId);

    // Set product name, product labels and product display name.
    // Multiple labels are also supported.
    Product product =
        Product.newBuilder()
            .setName(formattedName)
            .addProductLabels(
                KeyValue.newBuilder()
                    .setKey(productLabels.split(",")[0].split("=")[0])
                    .setValue(productLabels.split(",")[0].split("=")[1])
                    .build())
            .build();

    // Set product update field name.
    FieldMask updateMask = FieldMask.newBuilder().addPaths("product_labels").build();

    // Update the product.
    Product updatedProduct = client.updateProduct(product, updateMask);
    // Display the product information
    System.out.println(String.format("Product name: %s", updatedProduct.getName()));
    System.out.println(String.format("Updated product labels: "));
    for (Product.KeyValue element : updatedProduct.getProductLabelsList()) {
      System.out.println(String.format("%s: %s", element.getKey(), element.getValue()));
    }
  }
}

Node.js

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

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

  /**
   * 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 key = 'The key of the label';
  // const value = 'The value of the label';

  // Resource path that represents full path to the product.
  const productPath = client.productPath(projectId, location, productId);

  const product = {
    name: productPath,
    productLabels: [
      {
        key: key,
        value: value,
      },
    ],
  };

  const updateMask = {
    paths: ['product_labels'],
  };

  const request = {
    product: product,
    updateMask: updateMask,
  };

  const [updatedProduct] = await client.updateProduct(request);
  console.log(`Product name: ${updatedProduct.name}`);
  console.log(`Product display name: ${updatedProduct.displayName}`);
  console.log(`Product description: ${updatedProduct.description}`);
  console.log(`Product category: ${updatedProduct.productCategory}`);
  console.log(
    `Product Labels: ${updatedProduct.productLabels[0].key}: ${updatedProduct.productLabels[0].value}`
  );
}

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;
use Google\Cloud\Vision\V1\Product\KeyValue;
use Google\Cloud\Vision\V1\Product;
use Google\Protobuf\FieldMask;

/**
 * Update product labels
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productId ID of the product
 * @param string $key Key of the label to update
 * @param string $value Value of label to update
 */
function product_update($projectId, $location, $productId, $key, $value)
{
    $client = new ProductSearchClient();

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

    # set product name, product label and product display name.
    # multiple labels are also supported.
    $keyValue = (new KeyValue())
        ->setKey($key)
        ->setValue($value);
    $product = (new Product())
        ->setName($productPath)
        ->setProductLabels([$keyValue]);

    # updating only the product labels field here.
    $updateMask = (new FieldMask())
        ->setPaths(['product_labels']);

    # this overwrites the product_labels.
    $updatedProduct = $client->updateProduct($product, ['updateMask' => $updateMask]);

    # display the product information.
    printf('Product name: %s' . PHP_EOL, $updatedProduct->getName());
    print('Product labels: ' . PHP_EOL);
    foreach ($product->getProductLabels() as $label) {
        printf('%s : %s' . PHP_EOL, $label->getKey(), $label->getValue());
    }

    $client->close();
}

Python

from google.cloud import vision

def update_product_labels(
        project_id, location, product_id, key, value):
    """Update the product labels.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_id: Id of the product.
        key: The key of the label.
        value: The value of the label.
    """
    client = vision.ProductSearchClient()

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

    # Set product name, product label and product display name.
    # Multiple labels are also supported.
    key_value = vision.types.Product.KeyValue(key=key, value=value)
    product = vision.types.Product(
        name=product_path,
        product_labels=[key_value])

    # Updating only the product_labels field here.
    update_mask = vision.types.FieldMask(paths=['product_labels'])

    # This overwrites the product_labels.
    updated_product = client.update_product(
        product=product, update_mask=update_mask)

    # Display the updated product information.
    print('Product name: {}'.format(updated_product.name))
    print('Updated product labels: {}'.format(product.product_labels))

Ruby

require "google/cloud/vision"

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

  client = Google::Cloud::Vision.product_search

  product_path = client.product_path project:  project_id,
                                     location: location,
                                     product:  product_id
  product = {
    name:           product_path,
    product_labels: [{ key: "color", value: "green" }]
  }

  client.update_product product:     product,
                        update_mask: { "paths": ["product_labels"] }
end

응답

Product name: projects/prj-prod-search-tutorials/locations/us-east1/products/P_CLOTH-SHOE_46903668_070318
Product id: P_CLOTH-SHOE_46903668_070318
Product display name: Blue Dress
Updated product labels:
  Product label 1:
        key: style
        value: women
  Product label 2:
        key: category
        value: dress
  Product label 3:
        key: color
        value: blue
Product description: Short sleeved and 1950s style satin dress

5. 상품의 참조 이미지 만들기

개별 상품의 참조 이미지를 만들면 색인이 생성된 후에 이 이미지를 사용하여 Vision 상품검색에서 상품을 검색할 수 있습니다. 하나의 상품에 여러 개의 참조 이미지를 사용할 수 있으며, 특히 더 높은 일치 품질을 원하는 경우 이렇게 할 수 있습니다.

언제든지 상품에 새로운 참조 이미지를 추가할 수 있습니다.

참조 이미지를 만들 때 경계 폴리 좌표를 포함하는 옵션을 사용할 수 있습니다. 경계 폴리는 참조 이미지에서 관심 영역을 식별합니다. 예를 들어 재킷이라는 상품의 참조 이미지를 만드는 경우, 재킷의 좌표를 경계 폴리 인수에 제공하면 시스템에서 상품 일치를 찾을 때 재킷만 고려합니다. 참고: 쿼리 시간에는 API가 단일 경계 폴리만 지원하지만, 색인 시간에는 여러 경계 폴리를 제공할 수 있습니다.

이미지의 경계 폴리 좌표를 가져오는 간편한 방법은 Vision API 객체 현지화를 사용하는 것입니다. 객체 현지화에 대한 자세한 내용은 다중 객체 감지를 참조하세요.

REST 및 명령줄

아래의 요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: GCP 프로젝트 ID입니다.
  • location-id: 유효한 위치 식별자입니다. 유효한 위치 식별자는 us-west1, us-east1, europe-west1, asia-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 application-default print-access-token) \
-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 application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

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
        }
      ]
    }
  ]
}

C#

private static int CreateReferenceImage(CreateReferenceImageOptions opts)
{
    var client = ProductSearchClient.Create();
    var request = new CreateReferenceImageRequest
    {
        // Get the full path of the product.
        ParentAsProductName = new ProductName(opts.ProjectID,
                                              opts.ComputeRegion,
                                              opts.ProductID),
        ReferenceImageId = opts.ReferenceImageID,
        // Create a reference image.
        ReferenceImage = new ReferenceImage
        {
            Uri = opts.ReferenceImageURI
        }
    };

    var referenceImage = client.CreateReferenceImage(request);

    Console.WriteLine($"Reference image name: {referenceImage.Name}");
    Console.WriteLine($"Reference image URI: {referenceImage.Uri}");

    return 0;
}

Go


import (
	"context"
	"fmt"
	"io"

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

// 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: %v", 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: %v", err)
	}

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

	return nil
}

자바

/**
 * 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 =
        ProductSearchClient.formatProductName(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

async function createReferenceImage() {
  const vision = require('@google-cloud/vision');

  const client = new vision.ProductSearchClient();

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

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;
use Google\Cloud\Vision\V1\ReferenceImage;

/**
 * Create a reference image
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productId ID of the product
 * @param string $referenceImageId ID of the reference image
 * @param string $gcsUri Google Cloud Storage path of the input image
 */
function product_image_create($projectId, $location, $productId, $referenceImageId, $gcsUri)
{
    $client = new ProductSearchClient();

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

    # create a reference image.
    $referenceImage = (new ReferenceImage())
        ->setUri($gcsUri);

    # the response is the reference image with `name` populated.
    $image = $client->createReferenceImage($productPath, $referenceImage, ['referenceImageId' => $referenceImageId]);

    # display the reference image information
    printf('Reference image name: %s' . PHP_EOL, $image->getName());
    printf('Reference image uri: %s' . PHP_EOL, $image->getUri());

    $client->close();
}

Python

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.types.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('Reference image name: {}'.format(image.name))
    print('Reference image uri: {}'.format(image.uri))

Ruby

require "google/cloud/vision"

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

  client = Google::Cloud::Vision.product_search

  product_path = client.product_path project:  project_id,
                                     location: location,
                                     product:  product_id
  reference_image = {
    uri: "gs://cloud-samples-data/vision/product_search/shoes_1.jpg"
  }

  reference_image = client.create_reference_image parent:          product_path,
                                                  reference_image: reference_image

  puts "Added reference image to #{product_id}."
  puts "Reference image name: #{reference_image.name}"
  puts "Reference image uri: #{reference_image.uri}"
end

응답

Reference image name: projects/prj-prod-search-tutorials/locations/us-east1/products/P_CLOTH-SHOE_46903668_070318/referenceImages/I_469a896b70ba11e8be97d20059124800_070418
Reference image id: I_469a896b70ba11e8be97d20059124800_070418
Reference image uri: gs://product-search-tutorial/dress-shoe-dataset/469a896b70ba11e8be97d20059124800.jpg
Reference image bounding polygons:
vertices {
  x: 80
  y: 50
}
vertices {
  x: 80
  y: 660
}
vertices {
  x: 300
  y: 50
}
vertices {
  x: 430
  y: 660
}

2단계: 일치하는 상품 검색

이 인터페이스를 사용하면 새 이미지를 입력으로 사용하고 가장 일치하는 상품을 검색하여 만든 상품 카탈로그를 쿼리할 수 있습니다.

참조 이미지를 만들 때와 마찬가지로, 일치하는 이미지를 검색할 때 경계 폴리 좌표를 포함하는 옵션이 있습니다. 경계 폴리는 소스 이미지에서 일치하는 대상을 찾으려는 관심 영역을 식별합니다. 예를 들어 소스 이미지에 드레스와 핸드백이 모두 포함되어 있는데 드레스와 일치하는 항목만 찾으려면 사진에서 드레스만 포함된 영역의 경계 폴리 좌표를 식별합니다. 기본적으로 경계 폴리가 지정되지 않으면 API는 자동으로 가장 큰 경계 폴리를 정하고 이를 쿼리합니다.

이미지의 경계 폴리 좌표를 가져오는 간편한 방법은 Vision API 객체 현지화를 사용하는 것입니다. 객체 현지화에 대한 자세한 내용은 다중 객체 감지를 참조하세요. 예를 들어 전체 이미지 상자의 경계 폴리 [(0, 0), (0, 1), (1, 1), (1, 0)]를 지정하여 전체 이미지를 명시적으로 쿼리할 수 있습니다.

요청은 이미지와 가장 일치하는 상품과 함께 그 점수 및 일치하는 이미지가 포함된 API 응답을 반환합니다. 이 이미지는 가장 높은 신뢰값을 사용하여 반환됩니다.

REST 및 명령줄

아래의 요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • base64-encoded-image: 바이너리 이미지 데이터의 base64 표현(ASCII 문자열)입니다. 이 문자열은 다음 문자열과 비슷해야 합니다.
    • /9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q==
    자세한 내용은 base64 인코딩 주제를 참조하세요.
  • project-id: GCP 프로젝트 ID입니다.
  • location-id: 유효한 위치 식별자입니다. 유효한 위치 식별자는 us-west1, us-east1, europe-west1, asia-east1입니다.
  • product-set-id: 작업을 실행할 제품 세트의 ID입니다.

필드별 고려사항:

  • features.maxResults - 반환될 최대 결과 수입니다.
  • imageContext.productCategories - 검색할 제품 카테고리입니다. 현재는 하나의 제품 카테고리(homegoods, apparel, toys, package goods, general)만 지정할 수 있습니다.
  • imageContext.filter - 제품 라벨의 키-값 필터링 표현식 또는 여러 표현식입니다. 형식: 'key=value'.키-값 쌍 필터링을 AND 또는 OR 표현식 'color=blue AND style=mens' 또는 'color=blue OR color=black'과 연결할 수 있습니다. OR 표현식을 사용한다면 표현식 내의 모든 키가 반드시 동일해야 합니다.

HTTP 메서드 및 URL:

POST https://vision.googleapis.com/v1/images:annotate

JSON 요청 본문:

{
  "requests": [
    {
      "image": {
        "content": base64-encoded-image
      },
      "features": [
        {
          "type": "PRODUCT_SEARCH",
          "maxResults": 5
        }
      ],
      "imageContext": {
        "productSearchParams": {
          "productSet": "projects/project-id/locations/location-id/productSets/product-set-id",
          "productCategories": [
               "apparel"
          ],
          "filter": "style = womens"
        }
      }
    }
  ]
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://vision.googleapis.com/v1/images:annotate

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://vision.googleapis.com/v1/images:annotate" | Select-Object -Expand Content

요청이 성공하면 서버가 200 OK HTTP 상태 코드와 응답을 JSON 형식으로 반환합니다.

응답 JSON에는 다음과 같은 두 가지 결과 유형이 있습니다.

  • productSearchResults - 전체 이미지에 일치하는 제품의 목록을 포함합니다. 샘플 응답에서 일치하는 제품은 product_id65, product_id35, product_id34, product_id62, product_id32입니다.
  • productGroupedResults - 이미지에서 인식된 제품의 경계 상자 좌표와 일치 항목을 포함합니다. 응답 product_id65, product_id35, product_id34, product_id93, product_id62에는 식별된 제품이 한 개뿐이며 그 뒤로는 샘플 제품 조합에서 일치하는 제품이 나열되어 있습니다.

두 결과 유형에서 겹치는 부분이 있지만 차이가 있을 수도 있습니다(예: 응답의 product_id32와 product_id93).

C#

private static int GetSimilarProductsFile(GetSimilarProductsOptions opts)
{
    // Create annotate image request along with product search feature.
    Image image = Image.FromFile(opts.FilePath);
    var imageAnnotatorClient = ImageAnnotatorClient.Create();

    // Product Search specific parameters
    var productSearchParams = new ProductSearchParams
    {
        ProductSetAsProductSetName = new ProductSetName(opts.ProjectID,
                                                        opts.ComputeRegion,
                                                        opts.ProductSetId),
        ProductCategories = { opts.ProductCategory },
        Filter = opts.Filter
    };

    // Search products similar to the image.
    var results = imageAnnotatorClient.DetectSimilarProducts(image, productSearchParams);

    Console.WriteLine("Similar products:");
    foreach (var result in results.Results)
    {
        var product = result.Product;
        Console.WriteLine($"Score (Confidence): {result.Score}");
        Console.WriteLine($"Image name: {result.Image}");
        Console.WriteLine($"Product name: {product.Name}");
        Console.WriteLine($"Product display name: {product.DisplayName}");
        Console.WriteLine($"Product description: {product.Description}");
        Console.WriteLine($"Product labels: {product.ProductLabels}");
    }
    return 0;
}

Go


import (
	"context"
	"fmt"
	"io"
	"os"

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

// getSimilarProducts searches for products from a product set similar to products in an image file.
func getSimilarProducts(w io.Writer, projectID string, location string, productSetID string, productCategory string, file string, filter string) error {
	ctx := context.Background()
	c, err := vision.NewImageAnnotatorClient(ctx)
	if err != nil {
		return fmt.Errorf("NewImageAnnotatorClient: %v", err)
	}
	defer c.Close()

	f, err := os.Open(file)
	if err != nil {
		return fmt.Errorf("Open: %v", err)
	}
	defer f.Close()

	image, err := vision.NewImageFromReader(f)
	if err != nil {
		return fmt.Errorf("NewImageFromReader: %v", err)
	}

	ictx := &visionpb.ImageContext{
		ProductSearchParams: &visionpb.ProductSearchParams{
			ProductSet:        fmt.Sprintf("projects/%s/locations/%s/productSets/%s", projectID, location, productSetID),
			ProductCategories: []string{productCategory},
			Filter:            filter,
		},
	}

	response, err := c.ProductSearch(ctx, image, ictx)
	if err != nil {
		return fmt.Errorf("ProductSearch: %v", err)
	}

	fmt.Fprintf(w, "Product set index time:\n")
	fmt.Fprintf(w, "seconds: %d\n", response.IndexTime.Seconds)
	fmt.Fprintf(w, "nanos: %d\n", response.IndexTime.Nanos)

	fmt.Fprintf(w, "Search results:\n")
	for _, result := range response.Results {
		fmt.Fprintf(w, "Score(Confidence): %f\n", result.Score)
		fmt.Fprintf(w, "Image name: %s\n", result.Image)

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

	return nil
}

자바

/**
 * Search similar products to image in local file.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productSetId - Id of the product set.
 * @param productCategory - Category of the product.
 * @param filePath - Local file path of the image to be searched
 * @param filter - Condition to be applied on the labels. Example for filter: (color = red OR
 *     color = blue) AND style = kids It will search on all products with the following labels:
 *     color:red AND style:kids color:blue AND style:kids
 * @throws IOException - on I/O errors.
 */
public static void getSimilarProductsFile(
    String projectId,
    String computeRegion,
    String productSetId,
    String productCategory,
    String filePath,
    String filter)
    throws IOException {
  try (ImageAnnotatorClient queryImageClient = ImageAnnotatorClient.create()) {

    // Get the full path of the product set.
    String productSetPath =
        ProductSearchClient.formatProductSetName(projectId, computeRegion, productSetId);

    // Read the image as a stream of bytes.
    File imgPath = new File(filePath);
    byte[] content = Files.readAllBytes(imgPath.toPath());

    // Create annotate image request along with product search feature.
    Feature featuresElement = Feature.newBuilder().setType(Type.PRODUCT_SEARCH).build();
    // The input image can be a HTTPS link or Raw image bytes.
    // Example:
    // To use HTTP link replace with below code
    //  ImageSource source = ImageSource.newBuilder().setImageUri(imageUri).build();
    //  Image image = Image.newBuilder().setSource(source).build();
    Image image = Image.newBuilder().setContent(ByteString.copyFrom(content)).build();
    ImageContext imageContext =
        ImageContext.newBuilder()
            .setProductSearchParams(
                ProductSearchParams.newBuilder()
                    .setProductSet(productSetPath)
                    .addProductCategories(productCategory)
                    .setFilter(filter))
            .build();

    AnnotateImageRequest annotateImageRequest =
        AnnotateImageRequest.newBuilder()
            .addFeatures(featuresElement)
            .setImage(image)
            .setImageContext(imageContext)
            .build();
    List<AnnotateImageRequest> requests = Arrays.asList(annotateImageRequest);

    // Search products similar to the image.
    BatchAnnotateImagesResponse response = queryImageClient.batchAnnotateImages(requests);

    List<Result> similarProducts =
        response.getResponses(0).getProductSearchResults().getResultsList();
    System.out.println("Similar Products: ");
    for (Result product : similarProducts) {
      System.out.println(String.format("\nProduct name: %s", product.getProduct().getName()));
      System.out.println(
          String.format("Product display name: %s", product.getProduct().getDisplayName()));
      System.out.println(
          String.format("Product description: %s", product.getProduct().getDescription()));
      System.out.println(String.format("Score(Confidence): %s", product.getScore()));
      System.out.println(String.format("Image name: %s", product.getImage()));
    }
  }
}

Node.js

async function getSimilarProductsFile() {
  // Imports the Google Cloud client library
  const vision = require('@google-cloud/vision');
  const fs = require('fs');
  // Creates a client
  const productSearchClient = new vision.ProductSearchClient();
  const imageAnnotatorClient = new vision.ImageAnnotatorClient();

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'nodejs-docs-samples';
  // const location = 'us-west1';
  // const productSetId = 'indexed_product_set_id_for_testing';
  // const productCategory = 'apparel';
  // const filePath = './resources/shoes_1.jpg';
  // const filter = '';
  const productSetPath = productSearchClient.productSetPath(
    projectId,
    location,
    productSetId
  );
  const content = fs.readFileSync(filePath, 'base64');
  const request = {
    // The input image can be a GCS link or HTTPS link or Raw image bytes.
    // Example:
    // To use GCS link replace with below code
    // image: {source: {gcsImageUri: filePath}}    // To use HTTP link replace with below code
    // image: {source: {imageUri: filePath}}    image: {content: content},
    features: [{type: 'PRODUCT_SEARCH'}],
    imageContext: {
      productSearchParams: {
        productSet: productSetPath,
        productCategories: [productCategory],
        filter: filter,
      },
    },
  };
  const [response] = await imageAnnotatorClient.batchAnnotateImages({
    requests: [request],
  });
  console.log('Search Image:', filePath);
  const results = response['responses'][0]['productSearchResults']['results'];
  console.log('\nSimilar product information:');
  results.forEach(result => {
    console.log('Product id:', result['product'].name.split('/').pop(-1));
    console.log('Product display name:', result['product'].displayName);
    console.log('Product description:', result['product'].description);
    console.log('Product category:', result['product'].productCategory);
  });
}

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ImageAnnotatorClient;
use Google\Cloud\Vision\V1\ProductSearchClient;
use Google\Cloud\Vision\V1\ProductSearchParams;

/**
 * Search similar products to image
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productSetId ID of the product set
 * @param string $productCategory Category of the product
 * @param string $filePath Local file path of the image to be searched
 * @param string $filter Condition to be applied on the labels
 */
function product_search_similar($projectId, $location, $productSetId, $productCategory, $filePath, $filter)
{
    $imageAnnotatorClient = new ImageAnnotatorClient();
    $productSearchClient = new ProductSearchClient();

    # read the image
    $image = file_get_contents($filePath);

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

    # product search specific parameters
    $productSearchParams = (new ProductSearchParams())
        ->setProductSet($productSetPath)
        ->setProductCategories([$productCategory])
        ->setFilter($filter);

    # search products similar to the image
    $response = $imageAnnotatorClient->productSearch($image, $productSearchParams);

    if ($productSearchResults = $response->getProductSearchResults()) {
        $indexTime = $productSearchResults->getIndexTime();
        printf('Product set index time: %d seconds %d nanos' . PHP_EOL, $indexTime->getSeconds(), $indexTime->getNanos());

        $results = $productSearchResults->getResults();
        print('Search results: ' . PHP_EOL);
        foreach ($results as $result) {
            printf('Score (confidence): %d' . PHP_EOL, $result->getScore());

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

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

    $imageAnnotatorClient->close();
    $productSearchClient->close();
}

Python

from google.cloud import vision

def get_similar_products_file(
        project_id, location, product_set_id, product_category,
        file_path, filter):
    """Search similar products to image.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_set_id: Id of the product set.
        product_category: Category of the product.
        file_path: Local file path of the image to be searched.
        filter: Condition to be applied on the labels.
        Example for filter: (color = red OR color = blue) AND style = kids
        It will search on all products with the following labels:
        color:red AND style:kids
        color:blue AND style:kids
    """
    # product_search_client is needed only for its helper methods.
    product_search_client = vision.ProductSearchClient()
    image_annotator_client = vision.ImageAnnotatorClient()

    # Read the image as a stream of bytes.
    with open(file_path, 'rb') as image_file:
        content = image_file.read()

    # Create annotate image request along with product search feature.
    image = vision.types.Image(content=content)

    # product search specific parameters
    product_set_path = product_search_client.product_set_path(
        project=project_id, location=location,
        product_set=product_set_id)
    product_search_params = vision.types.ProductSearchParams(
        product_set=product_set_path,
        product_categories=[product_category],
        filter=filter)
    image_context = vision.types.ImageContext(
        product_search_params=product_search_params)

    # Search products similar to the image.
    response = image_annotator_client.product_search(
        image, image_context=image_context)

    index_time = response.product_search_results.index_time
    print('Product set index time:')
    print('  seconds: {}'.format(index_time.seconds))
    print('  nanos: {}\n'.format(index_time.nanos))

    results = response.product_search_results.results

    print('Search results:')
    for result in results:
        product = result.product

        print('Score(Confidence): {}'.format(result.score))
        print('Image name: {}'.format(result.image))

        print('Product name: {}'.format(product.name))
        print('Product display name: {}'.format(
            product.display_name))
        print('Product description: {}\n'.format(product.description))
        print('Product labels: {}\n'.format(product.product_labels))

Ruby

require "google/cloud/vision"

def product_search_get_similar_products \
    project_id       = "your-project-id",
    location         = "us-west1",
    product_set_id   = "your-product-set-id",
    product_category = "apparel",
    file_path        = "path/to/product_image.jpg",
    filter           = "(color = red OR color = blue) AND style = kids"

  product_search_client  = Google::Cloud::Vision.product_search
  image_annotator_client = Google::Cloud::Vision.image_annotator

  product_set_path = product_search_client.product_set_path(
    project:     project_id,
    location:    location,
    product_set: product_set_id
  )

  product_set = product_search_client.get_product_set name: product_set_path

  if product_set.index_time.seconds.zero?
    puts "Product set has not been indexed. Please wait and try again."
    return
  end

  product_search_params = {
    product_set:        product_set_path,
    product_categories: [product_category],
    filter:             filter
  }
  image_context = { product_search_params: product_search_params }

  response = image_annotator_client.product_search_detection(
    image:         file_path,
    image_context: image_context
  )

  display_similar_products response.responses.first.product_search_results
end

def display_similar_products search_results
  index_time = search_results.index_time
  puts "Product set index time:"
  puts "\tseconds: #{index_time.seconds}"
  puts "\tnanos: #{index_time.nanos}\n"

  puts "Search results:"
  search_results.results.each_with_index do |result, index|
    puts "Result #{index + 1}:"
    product = result.product

    puts "\tScore(Confidence): #{result.score}"
    puts "\tImage name: #{result.image}"

    puts "\tProduct name: #{product.name}"
    puts "\tProduct display name: #{product.display_name}"
    puts "\tProduct description: #{product.description}"
    puts "\tProduct labels: #{product.product_labels}"
  end
end

의류 응답 예시

Search Image:
  D:/product/final/images-20180618T073733Z-01/images/469355b570ba11e88ff2d20059124800.jpg

이미지 검색결과

Similar product information:
 Product id: 46930b6b
 Product display name: Evening gown
 Product description: Blue evening gown in 1940s style
 Product category: apparel
 style: women
 category: dress
 color: blue

라벨로 검색하기

다음 검색 예제에는 색상을 기반으로 하는 필터가 포함되어 있습니다.

요청

get_similar_products_file() 또는 get_similar_products_uri() 메서드를 사용하여 다음 요청을 실행하여 검색 요청을 수행합니다. 제품 세트 ID, 로컬 이미지 파일 경로, 필터가 인수로 전달됩니다. 이 입력 이미지는 'resources/input/'에도 있습니다.

Python

python product_search.py get_similar_products_file "12000002" "D:/product/final/images-20180618T073733Z-001/images/469355b570ba11e88ff2d20059124800.jpg" "color=white"

응답

Search Image:
  D:/product/final/images-20180618T073733Z-001/images/469355b570ba11e88ff2d20059124800.jpg

이미지 검색결과 2

Similar product information:
 Product id: p569d4e7a1
 Product display name: Wedding Dress
 Product description: Elegant Wedding Dress for women
 Product category: apparel
 style: women
 category: dress
 color: white