데이터 세트 생성 및 이미지 가져오기

데이터 세트에는 커스텀 모델이 사용할 카테고리 라벨로 지정해 분류하려는 콘텐츠 유형의 대표 샘플이 있습니다. 데이터 세트는 모델 학습을 위한 입력으로 사용됩니다.

데이터 세트 구축을 위한 주요 단계는 다음과 같습니다.

  1. 데이터 세트 생성 및 각 항목에 여러 개의 라벨을 적용할지 여부를 지정
  2. 데이터 세트로 데이터 항목 가져오기
  3. 항목 라벨 지정

이미 할당된 라벨이 있는 항목을 가져오면 2단계와 3단계가 결합됩니다.

데이터 세트 만들기

커스텀 모델을 생성하는 첫 단계는 모델 학습용 데이터를 저장할 비어 있는 데이터 세트를 만드는 것입니다. 데이터 세트를 생성할 때 커스텀 모델이 수행할 다음 분류 유형을 지정합니다.

  • MULTICLASS는 각 분류된 문서에 단일 라벨을 부여합니다.
  • MULTILABEL은 이미지에 다중 라벨을 부여합니다.

AutoML API의 v1 버전부터 이 요청은 장기 실행 작업의 ID를 반환합니다.

장기 실행 작업이 완료되면 이미지를 가져올 수 있습니다. 새로 만든 데이터 세트에는 이미지를 가져올 때까지는 어떤 데이터도 포함되지 않습니다.

데이터 세트로 이미지 가져오기나 모델 학습과 같은 다른 작업에 사용할 수 있도록 (응답에서) 새 데이터 세트의 데이터 세트 ID를 저장합니다.

웹 UI

  1. Vision 대시보드를 엽니다.

    Console의 왼쪽 탐색 메뉴 항목에서 인공지능 > Vision을 선택하여 이 페이지에 액세스할 수도 있습니다. 통합된 Vision 대시보드로 이동됩니다. AutoML Vision 카드를 선택합니다.

    통합 UI 비전 대시보드

  2. 왼쪽 탐색 메뉴에서 데이터 세트를 선택합니다.

  3. 페이지 상단의 새 데이터 세트 버튼을 선택하고 데이터 세트 이름을 업데이트한 후(선택사항) 보유한 데이터에 따라 단일 라벨 분류 또는 다중 라벨 분류를 선택합니다.

    데이터 세트의 모델 유형 선택 페이지

  4. 분류 유형을 지정한 후에 데이터 세트 만들기를 선택합니다.

  5. 데이터 세트 만들기 페이지에서 Google Cloud Storage의 CSV 파일 또는 로컬 이미지 파일을 선택하여 데이터 세트로 가져올 수 있습니다.

    CSV 가져오기 선택 창

    계속을 선택하여 데이터 세트로 이미지 가져오기를 시작합니다. 이미지를 가져오는 동안 데이터 세트 상태는 실행 중: 이미지 가져오기로 표시됩니다.

  6. 가져오기가 완료되면 이메일이 전송됩니다.

REST

다음 예시에서는 항목당 라벨 1개를 지원하는 데이터 세트를 만듭니다(MULTICLASS 참조).

새로 생성된 데이터 세트에는 항목을 가져올 때까지는 어떤 데이터도 포함되지 않습니다.

데이터 세트로 항목 가져오기나 모델 학습과 같은 다른 작업에 사용할 수 있도록 (응답에서) 새 데이터 세트의 "name"을 저장합니다.

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

  • project-id: GCP 프로젝트 ID입니다.
  • display-name: 선택한 문자열 표시 이름입니다.

HTTP 메서드 및 URL:

POST https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/datasets

JSON 요청 본문:

{
  "displayName": "DISPLAY_NAME",
  "imageClassificationDatasetMetadata": {
    "classificationType": "MULTICLASS"
  }
}

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

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://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/datasets"

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://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/datasets" | Select-Object -Expand Content

다음과 비슷한 출력이 표시됩니다. 작업 ID(이 경우 ICN3819960680614725486)를 사용하여 작업 상태를 가져올 수 있습니다. 예시를 보려면 장기 실행 작업 다루기를 참조하세요.

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/ICN3819960680614725486",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-11-14T16:49:13.667526Z",
    "updateTime": "2019-11-14T16:49:13.667526Z",
    "createDatasetDetails": {}
  }
}

장기 실행 작업이 완료되면 동일한 작업 상태 요청으로 데이터 세트의 ID를 가져올 수 있습니다. 응답은 다음과 비슷하게 표시됩니다.

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/ICN3819960680614725486",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-11-14T16:49:13.667526Z",
    "updateTime": "2019-11-14T16:49:17.975314Z",
    "createDatasetDetails": {}
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.Dataset",
    "name": "projects/PROJECT_ID/locations/us-central1/datasets/ICN5496445433112696489"
  }
}

Go

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// visionClassificationCreateDataset creates a dataset for image classification.
func visionClassificationCreateDataset(w io.Writer, projectID string, location string, datasetName string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// datasetName := "dataset_display_name"

	ctx := context.Background()
	client, err := automl.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &automlpb.CreateDatasetRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Dataset: &automlpb.Dataset{
			DisplayName: datasetName,
			DatasetMetadata: &automlpb.Dataset_ImageClassificationDatasetMetadata{
				ImageClassificationDatasetMetadata: &automlpb.ImageClassificationDatasetMetadata{
					// Specify the classification type:
					// - MULTILABEL: Multiple labels are allowed for one example.
					// - MULTICLASS: At most one label is allowed per example.
					ClassificationType: automlpb.ClassificationType_MULTILABEL,
				},
			},
		},
	}

	op, err := client.CreateDataset(ctx, req)
	if err != nil {
		return fmt.Errorf("CreateDataset: %w", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

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

	fmt.Fprintf(w, "Dataset name: %v\n", dataset.GetName())

	return nil
}

Java

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.ClassificationType;
import com.google.cloud.automl.v1.Dataset;
import com.google.cloud.automl.v1.ImageClassificationDatasetMetadata;
import com.google.cloud.automl.v1.LocationName;
import com.google.cloud.automl.v1.OperationMetadata;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

class VisionClassificationCreateDataset {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String displayName = "YOUR_DATASET_NAME";
    createDataset(projectId, displayName);
  }

  // Create a dataset
  static void createDataset(String projectId, String displayName)
      throws IOException, ExecutionException, InterruptedException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (AutoMlClient client = AutoMlClient.create()) {
      // A resource that represents Google Cloud Platform location.
      LocationName projectLocation = LocationName.of(projectId, "us-central1");

      // Specify the classification type
      // Types:
      // MultiLabel: Multiple labels are allowed for one example.
      // MultiClass: At most one label is allowed per example.
      ClassificationType classificationType = ClassificationType.MULTILABEL;
      ImageClassificationDatasetMetadata metadata =
          ImageClassificationDatasetMetadata.newBuilder()
              .setClassificationType(classificationType)
              .build();
      Dataset dataset =
          Dataset.newBuilder()
              .setDisplayName(displayName)
              .setImageClassificationDatasetMetadata(metadata)
              .build();
      OperationFuture<Dataset, OperationMetadata> future =
          client.createDatasetAsync(projectLocation, dataset);

      Dataset createdDataset = future.get();

      // Display the dataset information.
      System.out.format("Dataset name: %s\n", createdDataset.getName());
      // To get the dataset id, you have to parse it out of the `name` field. As dataset Ids are
      // required for other methods.
      // Name Form: `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}`
      String[] names = createdDataset.getName().split("/");
      String datasetId = names[names.length - 1];
      System.out.format("Dataset id: %s\n", datasetId);
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const displayName = 'YOUR_DISPLAY_NAME';

// Imports the Google Cloud AutoML library
const {AutoMlClient} = require('@google-cloud/automl').v1;

// Instantiates a client
const client = new AutoMlClient();

async function createDataset() {
  // Construct request
  // Specify the classification type
  // Types:
  // MultiLabel: Multiple labels are allowed for one example.
  // MultiClass: At most one label is allowed per example.
  const request = {
    parent: client.locationPath(projectId, location),
    dataset: {
      displayName: displayName,
      imageClassificationDatasetMetadata: {
        classificationType: 'MULTILABEL',
      },
    },
  };

  // Create dataset
  const [operation] = await client.createDataset(request);

  // Wait for operation to complete.
  const [response] = await operation.promise();

  console.log(`Dataset name: ${response.name}`);
  console.log(`
    Dataset id: ${
      response.name
        .split('/')
        [response.name.split('/').length - 1].split('\n')[0]
    }`);
}

createDataset();

Python

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# display_name = "your_datasets_display_name"

client = automl.AutoMlClient()

# A resource that represents Google Cloud Platform location.
project_location = f"projects/{project_id}/locations/us-central1"
# Specify the classification type
# Types:
# MultiLabel: Multiple labels are allowed for one example.
# MultiClass: At most one label is allowed per example.
# https://cloud.google.com/automl/docs/reference/rpc/google.cloud.automl.v1#classificationtype
metadata = automl.ImageClassificationDatasetMetadata(
    classification_type=automl.ClassificationType.MULTILABEL
)
dataset = automl.Dataset(
    display_name=display_name,
    image_classification_dataset_metadata=metadata,
)

# Create a dataset with the dataset metadata in the region.
response = client.create_dataset(
    parent=project_location, dataset=dataset, timeout=300
)

created_dataset = response.result()

# Display the dataset information
print(f"Dataset name: {created_dataset.name}")
print("Dataset id: {}".format(created_dataset.name.split("/")[-1]))

추가 언어

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

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

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

데이터 세트로 항목 가져오기

데이터세트를 만든 후에는 Google Cloud Storage 버킷에 저장된 CSV 파일에서 항목의 URI 및 라벨을 가져올 수 있습니다. 데이터 준비 및 가져올 CSV 파일 만들기에 대한 자세한 내용은 학습 데이터 준비를 참조하세요.

항목을 비어 있는 데이터 세트로 가져오거나 추가 항목을 기존 데이터 세트로 가져올 수 있습니다.

웹 UI

AutoML Vision UI를 사용하면 새 데이터 세트를 만들고 같은 페이지에서 항목을 가져올 수 있습니다. 데이터 세트 만들기를 참조하세요. 아래 단계는 항목을 기존 데이터 세트로 가져옵니다.

  1. Vision Dashboard를 열고 데이터 세트 페이지에서 데이터 세트를 선택합니다.

    데이터 세트 목록 페이지

  2. 이미지 페이지에서 제목 표시줄에 있는 항목 추가를 클릭하고 드롭다운 목록에서 가져오기 방법을 선택합니다.

    다음과 같은 작업을 수행할 수 있습니다.

    • 학습 이미지와 관련 카테고리 라벨을 포함하는 csv 파일을 로컬 컴퓨터 또는 Google Cloud Storage에서 업로드합니다.

    • 학습 이미지를 포함하는 .txt 또는 .zip 파일을 로컬 컴퓨터에서 업로드합니다.

  3. 가져올 파일을 선택합니다.

REST

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

  • project-id: GCP 프로젝트 ID입니다.
  • dataset-id: 데이터 세트의 ID입니다. ID는 데이터 세트 이름의 마지막 요소입니다. 예를 들면 다음과 같습니다.
    • 데이터 세트 이름: projects/project-id/locations/location-id/datasets/3104518874390609379
    • 데이터 세트 ID: 3104518874390609379
  • input-storage-path: Google Cloud Storage에 저장된 CSV 파일의 경로입니다. 요청하는 사용자에게 적어도 버킷에 대한 읽기 권한이 있어야 합니다.

HTTP 메서드 및 URL:

POST https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/datasets/DATASET_ID:importData

JSON 요청 본문:

{
  "inputConfig": {
    "gcsSource": {
      "inputUris": [INPUT_STORAGE_PATH]
    }
  }
}

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

curl

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

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/datasets/DATASET_ID:importData"

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://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/datasets/DATASET_ID:importData" | Select-Object -Expand Content

다음과 비슷한 출력이 표시됩니다. 작업 ID(이 경우 ICN3819960680614725486)를 사용하여 작업 상태를 가져올 수 있습니다. 예시를 보려면 장기 실행 작업 다루기를 참조하세요.

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2018-10-29T15:56:29.176485Z",
    "updateTime": "2018-10-29T15:56:29.176485Z",
    "importDataDetails": {}
  }
}

Go

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// importDataIntoDataset imports data into a dataset.
func importDataIntoDataset(w io.Writer, projectID string, location string, datasetID string, inputURI string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// datasetID := "TRL123456789..."
	// inputURI := "gs://BUCKET_ID/path_to_training_data.csv"

	ctx := context.Background()
	client, err := automl.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &automlpb.ImportDataRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/datasets/%s", projectID, location, datasetID),
		InputConfig: &automlpb.InputConfig{
			Source: &automlpb.InputConfig_GcsSource{
				GcsSource: &automlpb.GcsSource{
					InputUris: []string{inputURI},
				},
			},
		},
	}

	op, err := client.ImportData(ctx, req)
	if err != nil {
		return fmt.Errorf("ImportData: %w", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

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

	fmt.Fprintf(w, "Data imported.\n")

	return nil
}

Java

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.DatasetName;
import com.google.cloud.automl.v1.GcsSource;
import com.google.cloud.automl.v1.InputConfig;
import com.google.cloud.automl.v1.OperationMetadata;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

class ImportDataset {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String datasetId = "YOUR_DATASET_ID";
    String path = "gs://BUCKET_ID/path_to_training_data.csv";
    importDataset(projectId, datasetId, path);
  }

  // Import a dataset
  static void importDataset(String projectId, String datasetId, String path)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (AutoMlClient client = AutoMlClient.create()) {
      // Get the complete path of the dataset.
      DatasetName datasetFullId = DatasetName.of(projectId, "us-central1", datasetId);

      // Get multiple Google Cloud Storage URIs to import data from
      GcsSource gcsSource =
          GcsSource.newBuilder().addAllInputUris(Arrays.asList(path.split(","))).build();

      // Import data from the input URI
      InputConfig inputConfig = InputConfig.newBuilder().setGcsSource(gcsSource).build();
      System.out.println("Processing import...");

      // Start the import job
      OperationFuture<Empty, OperationMetadata> operation =
          client.importDataAsync(datasetFullId, inputConfig);

      System.out.format("Operation name: %s%n", operation.getName());

      // If you want to wait for the operation to finish, adjust the timeout appropriately. The
      // operation will still run if you choose not to wait for it to complete. You can check the
      // status of your operation using the operation's name.
      Empty response = operation.get(45, TimeUnit.MINUTES);
      System.out.format("Dataset imported. %s%n", response);
    } catch (TimeoutException e) {
      System.out.println("The operation's polling period was not long enough.");
      System.out.println("You can use the Operation's name to get the current status.");
      System.out.println("The import job is still running and will complete as expected.");
      throw e;
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const datasetId = 'YOUR_DISPLAY_ID';
// const path = 'gs://BUCKET_ID/path_to_training_data.csv';

// Imports the Google Cloud AutoML library
const {AutoMlClient} = require('@google-cloud/automl').v1;

// Instantiates a client
const client = new AutoMlClient();

async function importDataset() {
  // Construct request
  const request = {
    name: client.datasetPath(projectId, location, datasetId),
    inputConfig: {
      gcsSource: {
        inputUris: path.split(','),
      },
    },
  };

  // Import dataset
  console.log('Proccessing import');
  const [operation] = await client.importData(request);

  // Wait for operation to complete.
  const [response] = await operation.promise();
  console.log(`Dataset imported: ${response}`);
}

importDataset();

Python

이 샘플을 사용해 보기 전에 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# dataset_id = "YOUR_DATASET_ID"
# path = "gs://YOUR_BUCKET_ID/path/to/data.csv"

client = automl.AutoMlClient()
# Get the full path of the dataset.
dataset_full_id = client.dataset_path(project_id, "us-central1", dataset_id)
# Get the multiple Google Cloud Storage URIs
input_uris = path.split(",")
gcs_source = automl.GcsSource(input_uris=input_uris)
input_config = automl.InputConfig(gcs_source=gcs_source)
# Import data from the input URI
response = client.import_data(name=dataset_full_id, input_config=input_config)

print("Processing import...")
print(f"Data imported. {response.result()}")

학습 항목 라벨 지정하기

모델 학습에 유용하려면 데이터 세트에 있는 각 항목은 카테고리 라벨이 하나 이상 지정되어야 합니다. AutoML Vision은 카테고리 라벨이 없는 항목을 무시합니다. 다음 세 가지 방법으로 학습 항목에 라벨을 제공할 수 있습니다.

  1. CSV 파일에 라벨 포함
    • .csv 파일에서 항목 라벨을 지정하는 방법에 대한 자세한 내용은 학습 데이터 준비를 참조하세요.
  2. AutoML Vision UI에서 항목에 라벨을 지정합니다.
  3. Google의 AI Platform 데이터 라벨링 서비스와 같은 수동 라벨링 서비스를 통해 라벨 지정을 요청합니다.

UI에서 라벨 지정

웹 UI

AutoML Vision UI에서 항목에 라벨을 지정하려면 데이터 세트 등록 페이지에서 데이터 세트를 선택하여 세부정보를 확인합니다.

사이드 바에는 라벨이 지정된 항목과 라벨이 없는 항목의 수가 요약되어 있습니다. 여기에서 라벨별로 항목 목록을 필터링하거나 새 라벨 추가를 선택하여 새 라벨을 만들 수 있습니다.

이미지 페이지

이 화면에서 이미지 라벨을 추가하거나 변경할 수도 있습니다.

라벨을 추가하거나 변경할 이미지를 선택합니다.

이미지 라벨 추가 또는 변경 화면

라벨 지정 요청

Google의 AI Platform 데이터 라벨링 서비스 서비스를 사용하여 이미지에 라벨을 지정할 수 있습니다. 자세한 내용은 제품 문서를 참조하세요.

장기 실행 작업 다루기

다음 코드 샘플을 사용하여 장기 실행 작업의 상태를 가져올 수 있습니다.

REST

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

  • project-id: GCP 프로젝트 ID입니다.
  • operation-id: 작업의 ID입니다. ID는 작업 이름의 마지막 요소입니다. 예를 들면 다음과 같습니다.
    • 작업 이름: projects/project-id/locations/location-id/operations/IOD5281059901324392598
    • 작업 ID: IOD5281059901324392598

HTTP 메서드 및 URL:

GET https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID

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

curl

다음 명령어를 실행합니다.

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
"https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID"

PowerShell

다음 명령어를 실행합니다.

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

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID" | Select-Object -Expand Content
가져오기 작업이 완료되면 다음과 유사한 출력이 표시됩니다.
{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2018-10-29T15:56:29.176485Z",
    "updateTime": "2018-10-29T16:10:41.326614Z",
    "importDataDetails": {}
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.protobuf.Empty"
  }
}

모델 만들기 작업이 완료되면 다음과 유사한 출력이 표시됩니다.

{
  "name": "projects/PROJECT_ID/locations/us-central1/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-07-22T18:35:06.881193Z",
    "updateTime": "2019-07-22T19:58:44.972235Z",
    "createModelDetails": {}
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.Model",
    "name": "projects/PROJECT_ID/locations/us-central1/models/MODEL_ID"
  }
}

Go

이 샘플을 사용해 보기 전에 API 및 참조 > 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// getOperationStatus gets an operation's status.
func getOperationStatus(w io.Writer, projectID string, location string, datasetID string, modelName string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// datasetID := "ICN123456789..."
	// modelName := "model_display_name"

	ctx := context.Background()
	client, err := automl.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &automlpb.CreateModelRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Model: &automlpb.Model{
			DisplayName: modelName,
			DatasetId:   datasetID,
			ModelMetadata: &automlpb.Model_ImageClassificationModelMetadata{
				ImageClassificationModelMetadata: &automlpb.ImageClassificationModelMetadata{
					TrainBudgetMilliNodeHours: 1000, // 1000 milli-node hours are 1 hour
				},
			},
		},
	}

	op, err := client.CreateModel(ctx, req)
	if err != nil {
		return err
	}
	fmt.Fprintf(w, "Name: %v\n", op.Name())

	// Wait for the longrunning operation complete.
	resp, err := op.Wait(ctx)
	if err != nil && !op.Done() {
		fmt.Println("failed to fetch operation status", err)
		return err
	}
	if err != nil && op.Done() {
		fmt.Println("operation completed with error", err)
		return err
	}
	fmt.Fprintf(w, "Response: %v\n", resp)

	return nil
}

Java

이 샘플을 사용해 보기 전에 API 및 참조 > 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

import com.google.cloud.automl.v1.AutoMlClient;
import com.google.longrunning.Operation;
import java.io.IOException;

class GetOperationStatus {

  static void getOperationStatus() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String operationFullId = "projects/[projectId]/locations/us-central1/operations/[operationId]";
    getOperationStatus(operationFullId);
  }

  // Get the status of an operation
  static void getOperationStatus(String operationFullId) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (AutoMlClient client = AutoMlClient.create()) {
      // Get the latest state of a long-running operation.
      Operation operation = client.getOperationsClient().getOperation(operationFullId);

      // Display operation details.
      System.out.println("Operation details:");
      System.out.format("\tName: %s\n", operation.getName());
      System.out.format("\tMetadata Type Url: %s\n", operation.getMetadata().getTypeUrl());
      System.out.format("\tDone: %s\n", operation.getDone());
      if (operation.hasResponse()) {
        System.out.format("\tResponse Type Url: %s\n", operation.getResponse().getTypeUrl());
      }
      if (operation.hasError()) {
        System.out.println("\tResponse:");
        System.out.format("\t\tError code: %s\n", operation.getError().getCode());
        System.out.format("\t\tError message: %s\n", operation.getError().getMessage());
      }
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 API 및 참조 > 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const operationId = 'YOUR_OPERATION_ID';

// Imports the Google Cloud AutoML library
const {AutoMlClient} = require('@google-cloud/automl').v1;

// Instantiates a client
const client = new AutoMlClient();

async function getOperationStatus() {
  // Construct request
  const request = {
    name: `projects/${projectId}/locations/${location}/operations/${operationId}`,
  };

  const [response] = await client.operationsClient.getOperation(request);

  console.log(`Name: ${response.name}`);
  console.log('Operation details:');
  console.log(`${response}`);
}

getOperationStatus();

Python

이 샘플을 사용해 보기 전에 API 및 참조 > 클라이언트 라이브러리 페이지에서 언어 설정 안내를 따르세요.

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# operation_full_id = \
#     "projects/[projectId]/locations/us-central1/operations/[operationId]"

client = automl.AutoMlClient()
# Get the latest state of a long-running operation.
response = client._transport.operations_client.get_operation(operation_full_id)

print(f"Name: {response.name}")
print("Operation details:")
print(response)

추가 언어

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

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

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