라벨 인식

Vision API는 광범위한 카테고리 그룹에서 이미지 내 항목에 대한 정보를 인식하고 추출할 수 있습니다.

라벨은 일반 객체, 위치, 활동, 동물 종, 제품 등을 식별할 수 있습니다. 타겟팅 커스텀 라벨이 필요하면 Cloud AutoML Vision을 사용하여 커스텀 머신러닝 모델을 학습시켜 이미지를 분류할 수 있습니다.

라벨은 영어로만 반환됩니다. Cloud Translation API를 사용하면 영어 라벨을 다양한 기타 언어로 번역할 수 있습니다.

세타가야구 구 거리 이미지
이미지 크레딧: 알렉스 나이트, Unsplash

예를 들어 위 이미지는 다음과 같은 라벨 목록을 반환할 수 있습니다.

설명 점수
도로명 0.872
스냅샷 0.852
도시 0.848
야간 0.804
앨리 0.713

라벨 인식 요청

Google Cloud 프로젝트 및 인증 설정

로컬 이미지에서 라벨 인식

Vision API를 사용하여 로컬 이미지 파일에서 기능 감지를 수행할 수 있습니다.

REST 요청의 경우 이미지 파일의 콘텐츠를 요청 본문에 base64로 인코딩된 문자열로 보냅니다.

gcloud 및 클라이언트 라이브러리 요청의 경우 요청에 로컬 이미지 경로를 지정합니다.

REST

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

  • BASE64_ENCODED_IMAGE: 바이너리 이미지 데이터의 base64 표현(ASCII 문자열)입니다. 이 문자열은 다음 문자열과 유사하게 표시됩니다.
    • /9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q==
    자세한 내용은 base64 인코딩 주제를 참조하세요.
  • RESULTS_INT: (선택사항) 반환할 결과의 정수 값입니다. "maxResults" 필드와 해당 값을 생략하면 API에서 기본값 10개를 반환합니다. 이 필드는 TEXT_DETECTION, DOCUMENT_TEXT_DETECTION, CROP_HINTS 기능 유형에는 적용되지 않습니다.
  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
  "requests": [
    {
      "image": {
        "content": "BASE64_ENCODED_IMAGE"
      },
      "features": [
        {
          "maxResults": RESULTS_INT,
          "type": "LABEL_DETECTION"
        }
      ]
    }
  ]
}

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

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 형식으로 반환합니다.

LABEL_DETECTION 응답에는 인식된 라벨, 점수, 주제, 불분명한 라벨 ID가 포함됩니다. 각 항목의 의미는 다음과 같습니다.

  • mid가 존재하는 경우 이 필드에는 항목의 Google 지식 정보 항목에 해당하는 머신 생성 식별자(MID)가 포함됩니다. 참고: mid 값은 여러 언어에서 고유하게 유지되므로 이러한 값을 사용하여 각기 다른 언어의 항목을 묶을 수 있습니다. MID 값에 대해 알아보려면 Google Knowledge Graph API 문서를 참조하세요.
  • description - 라벨 설명입니다.
  • score - 신뢰도 점수의 범위는 0(신뢰도 없음)부터 1(신뢰도 매우 높음)까지입니다.
  • topicality - 이미지에 대한 ICA(이미지 콘텐츠 주석) 라벨의 관련성입니다. 페이지의 전체 문맥에 대한 라벨의 중요도 및 중심도를 측정합니다.


    {
  "responses": [
    {
      "labelAnnotations": [
        {
          "mid": "/m/01c8br",
          "description": "Street",
          "score": 0.87294734,
          "topicality": 0.87294734
        },
        {
          "mid": "/m/06pg22",
          "description": "Snapshot",
          "score": 0.8523099,
          "topicality": 0.8523099
        },
        {
          "mid": "/m/0dx1j",
          "description": "Town",
          "score": 0.8481104,
          "topicality": 0.8481104
        },
        {
          "mid": "/m/01d74z",
          "description": "Night",
          "score": 0.80408716,
          "topicality": 0.80408716
        },
        {
          "mid": "/m/01lwf0",
          "description": "Alley",
          "score": 0.7133322,
          "topicality": 0.7133322
        }
      ]
    }
  ]
}

Go

이 샘플을 사용해 보기 전에 Vision 빠른 시작: 클라이언트 라이브러리 사용Go 설정 안내를 따르세요. 자세한 내용은 Vision Go API 참고 문서를 참조하세요.

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


// detectLabels gets labels from the Vision API for an image at the given file path.
func detectLabels(w io.Writer, file string) error {
	ctx := context.Background()

	client, err := vision.NewImageAnnotatorClient(ctx)
	if err != nil {
		return err
	}

	f, err := os.Open(file)
	if err != nil {
		return err
	}
	defer f.Close()

	image, err := vision.NewImageFromReader(f)
	if err != nil {
		return err
	}
	annotations, err := client.DetectLabels(ctx, image, nil, 10)
	if err != nil {
		return err
	}

	if len(annotations) == 0 {
		fmt.Fprintln(w, "No labels found.")
	} else {
		fmt.Fprintln(w, "Labels:")
		for _, annotation := range annotations {
			fmt.Fprintln(w, annotation.Description)
		}
	}

	return nil
}

Java

이 샘플을 시도하기 전에 Vision API 빠른 시작: 클라이언트 라이브러리 사용의 자바 설정 안내를 따르세요. 자세한 내용은 Vision API 자바 참고 문서를 참조하세요.


import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.EntityAnnotation;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.protobuf.ByteString;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class DetectLabels {

  public static void detectLabels() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String filePath = "path/to/your/image/file.jpg";
    detectLabels(filePath);
  }

  // Detects labels in the specified local image.
  public static void detectLabels(String filePath) throws IOException {
    List<AnnotateImageRequest> requests = new ArrayList<>();

    ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath));

    Image img = Image.newBuilder().setContent(imgBytes).build();
    Feature feat = Feature.newBuilder().setType(Feature.Type.LABEL_DETECTION).build();
    AnnotateImageRequest request =
        AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
    requests.add(request);

    // 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 (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
      BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
      List<AnnotateImageResponse> responses = response.getResponsesList();

      for (AnnotateImageResponse res : responses) {
        if (res.hasError()) {
          System.out.format("Error: %s%n", res.getError().getMessage());
          return;
        }

        // For full list of available annotations, see http://g.co/cloud/vision/docs
        for (EntityAnnotation annotation : res.getLabelAnnotationsList()) {
          annotation
              .getAllFields()
              .forEach((k, v) -> System.out.format("%s : %s%n", k, v.toString()));
        }
      }
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 Vision 빠른 시작: 클라이언트 라이브러리 사용Node.js 설정 안내를 따르세요. 자세한 내용은 Vision Node.js API 참고 문서를 참조하세요.

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

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

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

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const fileName = 'Local image file, e.g. /path/to/image.png';

// Performs label detection on the local file
const [result] = await client.labelDetection(fileName);
const labels = result.labelAnnotations;
console.log('Labels:');
labels.forEach(label => console.log(label.description));

Python

이 샘플을 사용해 보기 전에 Vision 빠른 시작: 클라이언트 라이브러리 사용Python 설정 안내를 따르세요. 자세한 내용은 Vision Python API 참고 문서를 참조하세요.

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

def detect_labels(path):
    """Detects labels in the file."""
    from google.cloud import vision

    client = vision.ImageAnnotatorClient()

    with open(path, "rb") as image_file:
        content = image_file.read()

    image = vision.Image(content=content)

    response = client.label_detection(image=image)
    labels = response.label_annotations
    print("Labels:")

    for label in labels:
        print(label.description)

    if response.error.message:
        raise Exception(
            "{}\nFor more info on error messages, check: "
            "https://cloud.google.com/apis/design/errors".format(response.error.message)
        )

추가 언어

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

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

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

원격 이미지에서 라벨 인식

Vision API를 사용하여 Cloud Storage 또는 웹에 있는 원격 이미지 파일에서 기능 감지를 수행할 수 있습니다. 원격 파일 요청을 보내려면 요청 본문에 파일의 웹 URL 또는 Cloud Storage URI를 지정합니다.

REST

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

  • CLOUD_STORAGE_IMAGE_URI: Cloud Storage 버킷에 있는 유효한 이미지 파일의 경로입니다. 적어도 파일에 대한 읽기 권한이 있어야 합니다. 예를 들면 다음과 같습니다.
    • gs://cloud-samples-data/vision/label/setagaya.jpeg
  • RESULTS_INT: (선택사항) 반환할 결과의 정수 값입니다. "maxResults" 필드와 해당 값을 생략하면 API에서 기본값 10개를 반환합니다. 이 필드는 TEXT_DETECTION, DOCUMENT_TEXT_DETECTION, CROP_HINTS 기능 유형에는 적용되지 않습니다.
  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
  "requests": [
    {
      "image": {
        "source": {
          "gcsImageUri": "CLOUD_STORAGE_IMAGE_URI"
        }
      },
      "features": [
        {
          "maxResults": RESULTS_INT,
          "type": "LABEL_DETECTION"
        },
      ]
    }
  ]
}

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

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 형식으로 반환합니다.

LABEL_DETECTION 응답에는 인식된 라벨, 점수, 주제, 불분명한 라벨 ID가 포함됩니다. 각 항목의 의미는 다음과 같습니다.

  • mid가 존재하는 경우 이 필드에는 항목의 Google 지식 정보 항목에 해당하는 머신 생성 식별자(MID)가 포함됩니다. 참고: mid 값은 여러 언어에서 고유하게 유지되므로 이러한 값을 사용하여 각기 다른 언어의 항목을 묶을 수 있습니다. MID 값에 대해 알아보려면 Google Knowledge Graph API 문서를 참조하세요.
  • description - 라벨 설명입니다.
  • score - 신뢰도 점수의 범위는 0(신뢰도 없음)부터 1(신뢰도 매우 높음)까지입니다.
  • topicality - 이미지 콘텐츠 주석(ICA) 라벨과 이미지의 관련성입니다. 페이지의 전체 문맥에 대한 라벨의 중요도 및 중심도를 측정합니다.


    {
  "responses": [
    {
      "labelAnnotations": [
        {
          "mid": "/m/01c8br",
          "description": "Street",
          "score": 0.87294734,
          "topicality": 0.87294734
        },
        {
          "mid": "/m/06pg22",
          "description": "Snapshot",
          "score": 0.8523099,
          "topicality": 0.8523099
        },
        {
          "mid": "/m/0dx1j",
          "description": "Town",
          "score": 0.8481104,
          "topicality": 0.8481104
        },
        {
          "mid": "/m/01d74z",
          "description": "Night",
          "score": 0.80408716,
          "topicality": 0.80408716
        },
        {
          "mid": "/m/01lwf0",
          "description": "Alley",
          "score": 0.7133322,
          "topicality": 0.7133322
        }
      ]
    }
  ]
}

Go

이 샘플을 사용해 보기 전에 Vision 빠른 시작: 클라이언트 라이브러리 사용Go 설정 안내를 따르세요. 자세한 내용은 Vision Go API 참고 문서를 참조하세요.

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


// detectLabels gets labels from the Vision API for an image at the given file path.
func detectLabelsURI(w io.Writer, file string) error {
	ctx := context.Background()

	client, err := vision.NewImageAnnotatorClient(ctx)
	if err != nil {
		return err
	}

	image := vision.NewImageFromURI(file)
	annotations, err := client.DetectLabels(ctx, image, nil, 10)
	if err != nil {
		return err
	}

	if len(annotations) == 0 {
		fmt.Fprintln(w, "No labels found.")
	} else {
		fmt.Fprintln(w, "Labels:")
		for _, annotation := range annotations {
			fmt.Fprintln(w, annotation.Description)
		}
	}

	return nil
}

Java

이 샘플을 시도하기 전에 Vision API 빠른 시작: 클라이언트 라이브러리 사용의 자바 설정 안내를 따르세요. 자세한 내용은 Vision API 자바 참고 문서를 참조하세요.


import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.EntityAnnotation;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.ImageSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class DetectLabelsGcs {

  public static void detectLabelsGcs() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String filePath = "gs://your-gcs-bucket/path/to/image/file.jpg";
    detectLabelsGcs(filePath);
  }

  // Detects labels in the specified remote image on Google Cloud Storage.
  public static void detectLabelsGcs(String gcsPath) throws IOException {
    List<AnnotateImageRequest> requests = new ArrayList<>();

    ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
    Image img = Image.newBuilder().setSource(imgSource).build();
    Feature feat = Feature.newBuilder().setType(Feature.Type.LABEL_DETECTION).build();
    AnnotateImageRequest request =
        AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
    requests.add(request);

    // 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 (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
      BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
      List<AnnotateImageResponse> responses = response.getResponsesList();

      for (AnnotateImageResponse res : responses) {
        if (res.hasError()) {
          System.out.format("Error: %s%n", res.getError().getMessage());
          return;
        }

        // For full list of available annotations, see http://g.co/cloud/vision/docs
        for (EntityAnnotation annotation : res.getLabelAnnotationsList()) {
          annotation
              .getAllFields()
              .forEach((k, v) -> System.out.format("%s : %s%n", k, v.toString()));
        }
      }
    }
  }
}

Node.js

이 샘플을 사용해 보기 전에 Vision 빠른 시작: 클라이언트 라이브러리 사용Node.js 설정 안내를 따르세요. 자세한 내용은 Vision Node.js API 참고 문서를 참조하세요.

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

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

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Bucket where the file resides, e.g. my-bucket';
// const fileName = 'Path to file within bucket, e.g. path/to/image.png';

// Performs label detection on the gcs file
const [result] = await client.labelDetection(
  `gs://${bucketName}/${fileName}`
);
const labels = result.labelAnnotations;
console.log('Labels:');
labels.forEach(label => console.log(label.description));

Python

이 샘플을 사용해 보기 전에 Vision 빠른 시작: 클라이언트 라이브러리 사용Python 설정 안내를 따르세요. 자세한 내용은 Vision Python API 참고 문서를 참조하세요.

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

def detect_labels_uri(uri):
    """Detects labels in the file located in Google Cloud Storage or on the
    Web."""
    from google.cloud import vision

    client = vision.ImageAnnotatorClient()
    image = vision.Image()
    image.source.image_uri = uri

    response = client.label_detection(image=image)
    labels = response.label_annotations
    print("Labels:")

    for label in labels:
        print(label.description)

    if response.error.message:
        raise Exception(
            "{}\nFor more info on error messages, check: "
            "https://cloud.google.com/apis/design/errors".format(response.error.message)
        )

gcloud

이미지에서 라벨을 인식하려면 gcloud ml vision detect-labels 명령어를 사용합니다. 예를 들면 다음과 같습니다.

gcloud ml vision detect-labels gs://cloud-samples-data/vision/label/setagaya.jpeg

추가 언어

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

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

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

사용해 보기

아래에서 라벨 인식을 사용해보세요. 이미 지정된 이미지(gs://cloud-samples-data/vision/label/setagaya.jpeg)를 사용하거나 자체 이미지를 대신 지정할 수도 있습니다. 실행을 선택하여 요청을 보냅니다.

세타가야구 구 거리 이미지
이미지 크레딧: 알렉스 나이트, Unsplash

요청 본문:

{
  "requests": [
    {
      "features": [
        {
          "maxResults": 5,
          "type": "LABEL_DETECTION"
        }
      ],
      "image": {
        "source": {
          "imageUri": "gs://cloud-samples-data/vision/label/setagaya.jpeg"
        }
      }
    }
  ]
}