개별 예측 실행

모델을 만들어 학습시키고 배포한 후에는 해당 모델에 온라인 또는 동기식 예측 요청을 할 수 있습니다.

온라인(개별) 예측 예시

학습된 모델을 배포한 후에는 predict 메서드를 사용하여 이미지에 대한 예측을 요청하거나 UI를 사용하여 예측 주석을 가져올 수 있습니다. predict 메서드는 이미지에서 객체 경계 상자에 라벨을 적용합니다.

모델 배포 중에는 비용이 발생합니다. 모델 호스팅 사용 요금이 더 이상 발생하지 않도록 하려면 학습된 모델로 예측을 수행한 후에 모델을 배포 취소하면 됩니다.

웹 UI

  1. AutoML Vision 객체 감지 UI를 열고 왼쪽 탐색 메뉴에서 모델 탭(전구 아이콘이 있음)을 클릭하여 사용 가능한 모델을 표시합니다.

    다른 프로젝트의 모델을 보려면 제목 표시줄 오른쪽 위에 있는 드롭다운 목록에서 프로젝트를 선택하세요.

  2. 이미지에 라벨을 지정하는 데 사용할 모델의 행을 클릭합니다.

  3. 모델이 아직 배포되지 않았다면 모델 배포를 선택하여 지금 배포합니다.

    온라인 예측을 사용하려면 모델을 배포해야 합니다. 모델을 배포하면 비용이 발생합니다. 자세한 내용은 가격 책정 페이지를 참조하세요.

  4. 제목 표시줄 바로 아래에 있는 테스트 및 사용 탭을 클릭합니다.

    모델 테스트 및 사용 페이지

  5. 이미지 업로드를 클릭하여 라벨을 지정할 이미지를 업로드합니다.

    업로드된 이미지 예측 페이지

REST

예측을 테스트하려면 먼저 클라우드 호스팅 모델을 배포해야 합니다.

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

  • project-id: GCP 프로젝트 ID입니다.
  • model-id: 모델을 만들 때의 응답에서 모델의 ID입니다. ID는 모델 이름의 마지막 요소입니다. 예를 들면 다음과 같습니다.
    • 모델 이름: projects/project-id/locations/location-id/models/IOD4412217016962778756
    • 모델 ID: IOD4412217016962778756
  • base64-encoded-image: 바이너리 이미지 데이터의 base64 표현(ASCII 문자열)입니다. 이 문자열은 /9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q== 문자열과 비슷해야 합니다. 자세한 내용은 base64 인코딩 주제를 참조하세요.

필드별 고려사항:

  • scoreThreshold - 0~1 사이의 값입니다. 최소 점수 임곗값이 있는 값에만 이 값이 표시됩니다. 기본값은 0.5입니다.
  • maxBoundingBoxCount - 응답에서 반환될 경계 상자의 가장 큰 숫자(상한값)입니다. 기본값은 100이고 최댓값은 500입니다. 이 값은 리소스 제약조건을 따르며, 서버에 의해 제한될 수 있습니다.

HTTP 메서드 및 URL:

POST https://automl.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/models/MODEL_ID:predict

JSON 요청 본문:

{
  "payload": {
    "image": {
      "imageBytes": "BASE64_ENCODED_IMAGE"
    }
  },
  "params": {
    "scoreThreshold": "0.5",
    "maxBoundingBoxCount": "100"
  }
}

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

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/models/MODEL_ID:predict"

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/models/MODEL_ID:predict" | Select-Object -Expand Content

출력은 JSON 형식으로 반환됩니다. AutoML Vision 객체 감지 모델의 예측은 payload 필드에 포함됩니다.

  • 객체의 boundingBox는 대각선으로 마주하는 꼭짓점으로 지정됩니다.
  • displayName은 AutoML Vision 객체 감지 모델이 예측한 객체의 라벨입니다.
  • score는 지정한 라벨이 이미지에 적용하는 신뢰도 수준입니다. 범위는 0(신뢰도 없음)~1(신뢰도 높음)입니다.

{
  "payload": [
    {
      "imageObjectDetection": {
        "boundingBox": {
          "normalizedVertices": [
            {
              "x": 0.034553755,
              "y": 0.015524037
            },
            {
              "x": 0.941527,
              "y": 0.9912563
            }
          ]
        },
        "score": 0.9997793
      },
      "displayName": "Salad"
    },
    {
      "imageObjectDetection": {
        "boundingBox": {
          "normalizedVertices": [
            {
              "x": 0.11737197,
              "y": 0.7098793
            },
            {
              "x": 0.510878,
              "y": 0.87987
            }
          ]
        },
        "score": 0.63219965
      },
      "displayName": "Tomato"
    }
  ]
}

Go

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

import (
	"context"
	"fmt"
	"io"
	"io/ioutil"
	"os"

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

// visionObjectDetectionPredict does a prediction for image classification.
func visionObjectDetectionPredict(w io.Writer, projectID string, location string, modelID string, filePath string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// modelID := "IOD123456789..."
	// filePath := "path/to/image.jpg"

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

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

	req := &automlpb.PredictRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/models/%s", projectID, location, modelID),
		Payload: &automlpb.ExamplePayload{
			Payload: &automlpb.ExamplePayload_Image{
				Image: &automlpb.Image{
					Data: &automlpb.Image_ImageBytes{
						ImageBytes: bytes,
					},
				},
			},
		},
		// Params is additional domain-specific parameters.
		Params: map[string]string{
			// score_threshold is used to filter the result.
			"score_threshold": "0.8",
		},
	}

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

	for _, payload := range resp.GetPayload() {
		fmt.Fprintf(w, "Predicted class name: %v\n", payload.GetDisplayName())
		fmt.Fprintf(w, "Predicted class score: %v\n", payload.GetImageObjectDetection().GetScore())
		boundingBox := payload.GetImageObjectDetection().GetBoundingBox()
		fmt.Fprintf(w, "Normalized vertices:\n")
		for _, vertex := range boundingBox.GetNormalizedVertices() {
			fmt.Fprintf(w, "\tX: %v, Y: %v\n", vertex.GetX(), vertex.GetY())
		}
	}

	return nil
}

Java

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

import com.google.cloud.automl.v1.AnnotationPayload;
import com.google.cloud.automl.v1.BoundingPoly;
import com.google.cloud.automl.v1.ExamplePayload;
import com.google.cloud.automl.v1.Image;
import com.google.cloud.automl.v1.ModelName;
import com.google.cloud.automl.v1.NormalizedVertex;
import com.google.cloud.automl.v1.PredictRequest;
import com.google.cloud.automl.v1.PredictResponse;
import com.google.cloud.automl.v1.PredictionServiceClient;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

class VisionObjectDetectionPredict {

  static void predict() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    String filePath = "path_to_local_file.jpg";
    predict(projectId, modelId, filePath);
  }

  static void predict(String projectId, String modelId, String filePath) 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 (PredictionServiceClient client = PredictionServiceClient.create()) {
      // Get the full path of the model.
      ModelName name = ModelName.of(projectId, "us-central1", modelId);
      ByteString content = ByteString.copyFrom(Files.readAllBytes(Paths.get(filePath)));
      Image image = Image.newBuilder().setImageBytes(content).build();
      ExamplePayload payload = ExamplePayload.newBuilder().setImage(image).build();
      PredictRequest predictRequest =
          PredictRequest.newBuilder()
              .setName(name.toString())
              .setPayload(payload)
              .putParams(
                  "score_threshold", "0.5") // [0.0-1.0] Only produce results higher than this value
              .build();

      PredictResponse response = client.predict(predictRequest);
      for (AnnotationPayload annotationPayload : response.getPayloadList()) {
        System.out.format("Predicted class name: %s\n", annotationPayload.getDisplayName());
        System.out.format(
            "Predicted class score: %.2f\n",
            annotationPayload.getImageObjectDetection().getScore());
        BoundingPoly boundingPoly = annotationPayload.getImageObjectDetection().getBoundingBox();
        System.out.println("Normalized Vertices:");
        for (NormalizedVertex vertex : boundingPoly.getNormalizedVerticesList()) {
          System.out.format("\tX: %.2f, Y: %.2f\n", vertex.getX(), vertex.getY());
        }
      }
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const modelId = 'YOUR_MODEL_ID';
// const filePath = 'path_to_local_file.jpg';

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

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

// Read the file content for translation.
const content = fs.readFileSync(filePath);

async function predict() {
  // Construct request
  // params is additional domain-specific parameters.
  // score_threshold is used to filter the result
  const request = {
    name: client.modelPath(projectId, location, modelId),
    payload: {
      image: {
        imageBytes: content,
      },
    },
    params: {
      score_threshold: '0.8',
    },
  };

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

  for (const annotationPayload of response.payload) {
    console.log(`Predicted class name: ${annotationPayload.displayName}`);
    console.log(
      `Predicted class score: ${annotationPayload.imageObjectDetection.score}`
    );
    console.log('Normalized vertices:');
    for (const vertex of annotationPayload.imageObjectDetection.boundingBox
      .normalizedVertices) {
      console.log(`\tX: ${vertex.x}, Y: ${vertex.y}`);
    }
  }
}

predict();

Python

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

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# model_id = "YOUR_MODEL_ID"
# file_path = "path_to_local_file.jpg"

prediction_client = automl.PredictionServiceClient()

# Get the full path of the model.
model_full_id = automl.AutoMlClient.model_path(project_id, "us-central1", model_id)

# Read the file.
with open(file_path, "rb") as content_file:
    content = content_file.read()

image = automl.Image(image_bytes=content)
payload = automl.ExamplePayload(image=image)

# params is additional domain-specific parameters.
# score_threshold is used to filter the result
# https://cloud.google.com/automl/docs/reference/rpc/google.cloud.automl.v1#predictrequest
params = {"score_threshold": "0.8"}

request = automl.PredictRequest(name=model_full_id, payload=payload, params=params)

response = prediction_client.predict(request=request)
print("Prediction results:")
for result in response.payload:
    print(f"Predicted class name: {result.display_name}")
    print(f"Predicted class score: {result.image_object_detection.score}")
    bounding_box = result.image_object_detection.bounding_box
    print("Normalized Vertices:")
    for vertex in bounding_box.normalized_vertices:
        print(f"\tX: {vertex.x}, Y: {vertex.y}")

추가 언어

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

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

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