상품검색 튜토리얼

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

이 튜토리얼에서는 다음과 같은 방법을 알아봅니다.

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

시작하기 전에

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

라이브러리 가져오기

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

Go

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Go API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import (
	"context"
	"fmt"
	"io"

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

Java

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Java API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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.LocationName;
import com.google.cloud.vision.v1.ProductSearchClient;
import com.google.cloud.vision.v1.ReferenceImage;
import java.io.PrintStream;
import javax.swing.JPanel;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import net.sourceforge.argparse4j.inf.Subparsers;

Node.js

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Node.js API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

Python

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Python API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import vision

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 Vision API 제품 검색 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 Vision API 제품 검색 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Vision API 제품 검색 참조 문서를 참조하세요.

애플리케이션 실행

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

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

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

온라인 (개별) 가져오기

1. 상품 세트 만들기

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

요청

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

REST

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

  • PROJECT_ID: Google Cloud 프로젝트 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 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"

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

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

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

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

Go

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Go API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import (
	"context"
	"fmt"
	"io"

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

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

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

	return nil
}

Java

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Java API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Node.js API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

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

async function createProductSet() {
  /**
   * 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}`);
}
createProductSet();

Python

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Python API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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 = f"projects/{project_id}/locations/{location}"

    # Create a product set with the product set specification in the region.
    product_set = vision.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(f"Product set name: {response.name}")

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 Vision API 제품 검색 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 Vision API 제품 검색 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Vision API 제품 검색 참조 문서를 참조하세요.

응답

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: Google Cloud 프로젝트 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 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"

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

Go

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Go API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import (
	"context"
	"fmt"
	"io"

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

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

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

	return nil
}

Java

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Java API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Node.js API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

// Creates a client
const client = new vision.ProductSearchClient();
async function createProduct() {
  /**
   * 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}`);
}
createProduct();

Python

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Python API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

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 = f"projects/{project_id}/locations/{location}"

    # Create a product with the product specification in the region.
    # Set product display name and product category.
    product = vision.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(f"Product name: {response.name}")

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 Vision API 제품 검색 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 Vision API 제품 검색 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Vision API 제품 검색 참조 문서를 참조하세요.

응답

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: Google Cloud 프로젝트 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 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/product-set-id:addProduct"

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

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

{}

Go

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Go API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import (
	"context"
	"fmt"
	"io"

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

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

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

	return nil
}

Java

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Java API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Node.js API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

const vision = require('@google-cloud/vision');
const client = new vision.ProductSearchClient();

async function addProductToProductSet() {
  /**
   * 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.');
}
addProductToProductSet();

Python

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Python API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 Vision API 제품 검색 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 Vision API 제품 검색 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Vision API 제품 검색 참조 문서를 참조하세요.

응답

Product added to product set.

4. 상품 업데이트

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

명령줄

PATCH 요청을 전송하면 변경할 수 없는 productCategory 필드를 제외하고 모든 이전 필드 및 해당 값이 지워집니다. PATCH 업데이트 요청을 수행할 때 값에 필요한 모든 필드를 전송합니다.

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

  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.
  • LOCATION_ID: 유효한 위치 식별자입니다. 유효한 위치 식별자는 us-west1, us-east1, europe-west1, asia-east1입니다.
  • PRODUCT_ID: 참조 이미지와 연결된 제품의 ID입니다. 이 ID는 제품 생성 시 무작위로 설정되거나 사용자가 지정합니다.
  • display-name: 선택한 문자열 표시 이름입니다. 이전 표시 이름과 동일하거나 업데이트된 값일 수 있습니다.
  • description: 선택한 문자열 설명입니다. 이전 표시 이름과 동일하거나 업데이트된 값일 수 있습니다. 필요하지 않으면 description 필드와 값을 생략합니다.
  • productLabels: 제품과 연결된 하나 이상의 키-값 쌍입니다. 각 KEY_STRING에는 연결된 VALUE_STRING이 있어야 합니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

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

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

curl

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

curl -X PATCH \
-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"

PowerShell

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

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

Invoke-WebRequest `
-Method PATCH `
-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" | Select-Object -Expand Content

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

{
  "name": "projects/project-id/locations/location-id/products/product-id",
  "displayName": "display-name",
  "description": "description",
  "productCategory": "apparel-v2",
  "productLabels": [
    {
      "key": "style",
      "value": "womens"
    },
    {
      "key": "onSale",
      "value": "true"
    }
  ]
}

Go

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Go API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"cloud.google.com/go/vision/v2/apiv1/visionpb"
	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: %w", 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: %w", err)
	}

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

	return nil
}

Java

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Java API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Node.js API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

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

async function updateProductLabels() {
  /**
   * 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}`
  );
}
updateProductLabels();

Python

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Python API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

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.Product.KeyValue(key=key, value=value)
    product = vision.Product(name=product_path, product_labels=[key_value])

    # Updating only the product_labels field here.
    update_mask = field_mask.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(f"Product name: {updated_product.name}")
    print(f"Updated product labels: {product.product_labels}")

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 Vision API 제품 검색 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 Vision API 제품 검색 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Vision API 제품 검색 참조 문서를 참조하세요.

응답

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 제품 검색에서 제품을 검색할 수 있습니다. 하나의 제품에 여러 개의 참조 이미지를 사용할 수 있으며, 특히 더 높은 일치 품질을 원하는 경우 이렇게 할 수 있습니다.

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

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

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

REST

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

  • PROJECT_ID: Google Cloud 프로젝트 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 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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Go API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Java API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * 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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Node.js API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Python API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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 제품 검색 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 Vision API 제품 검색 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Vision API 제품 검색 참조 문서를 참조하세요.

응답

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: Google Cloud 프로젝트 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 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/images:annotate"

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/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).

Go

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Go API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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

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

// 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: %w", err)
	}
	defer c.Close()

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

	image, err := vision.NewImageFromReader(f)
	if err != nil {
		return fmt.Errorf("NewImageFromReader: %w", 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: %w", 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
}

Java

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Java API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Node.js API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

async function getSimilarProductsFile() {
  /**
   * 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);
  });
}
getSimilarProductsFile();

Python

Vision API 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Python API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import vision

def get_similar_products_file(
    project_id,
    location,
    product_set_id,
    product_category,
    file_path,
    filter,
    max_results,
):
    """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
        max_results: The maximum number of results (matches) to return. If omitted, all results are returned.
    """
    # 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.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.ProductSearchParams(
        product_set=product_set_path,
        product_categories=[product_category],
        filter=filter,
    )
    image_context = vision.ImageContext(product_search_params=product_search_params)

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

    index_time = response.product_search_results.index_time
    print("Product set index time: ")
    print(index_time)

    results = response.product_search_results.results

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

        print(f"Score(Confidence): {result.score}")
        print(f"Image name: {result.image}")

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

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 다음 .NET용 Vision API 제품 검색 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 Vision API 제품 검색 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Vision API 제품 검색 참조 문서를 참조하세요.

의류 응답 예시

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