Vision 클라이언트 라이브러리

이 페이지에서는 Vision API용 Cloud 클라이언트 라이브러리를 시작하는 방법을 설명합니다. 클라이언트 라이브러리를 사용하면 지원되는 언어로 Google Cloud API에 쉽게 액세스할 수 있습니다. 원시 요청을 서버에 보내 Google Cloud API를 직접 사용할 수 있지만 클라이언트 라이브러리는 작성해야 하는 코드 양을 크게 줄여 주는 간소화 기능을 제공합니다.

클라이언트 라이브러리 설명에서 Cloud 클라이언트 라이브러리 및 이전 Google API 클라이언트 라이브러리에 대해 자세히 알아보세요.

클라이언트 라이브러리 설치

C++

이 클라이언트 라이브러리 요구사항 및 설치 종속 항목에 대한 자세한 내용은 C++ 개발 환경 설정을 참조하세요.

C#

Visual Studio 2017 이상을 사용하는 경우 Nuget 패키지 관리자 창을 열고 다음을 입력합니다.

Install-Package Google.Apis

.NET Core 명령줄 인터페이스 도구를 사용하여 종속 항목을 설치하려면 다음 명령어를 실행합니다.

dotnet add package Google.Apis

자세한 내용은 C# 개발 환경 설정을 참조하세요.

Go

go get cloud.google.com/go/vision/apiv1

자세한 내용은 Go 개발 환경 설정을 참조하세요.

Java

Maven을 사용하는 경우 pom.xml 파일에 다음을 추가합니다. BOM에 대한 자세한 내용은 Google Cloud Platform 라이브러리 BOM을 참조하세요.

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.37.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-vision</artifactId>
  </dependency>

Gradle을 사용하는 경우 종속 항목에 다음을 추가합니다.

implementation 'com.google.cloud:google-cloud-vision:3.39.0'

SBT를 사용하는 경우 종속 항목에 다음을 추가합니다.

libraryDependencies += "com.google.cloud" % "google-cloud-vision" % "3.39.0"

Visual Studio Code, IntelliJ 또는 Eclipse를 사용하는 경우 다음 IDE 플러그인을 사용하여 클라이언트 라이브러리를 프로젝트에 추가할 수 있습니다.

이 플러그인은 서비스 계정의 키 관리와 같은 추가 기능을 제공합니다. 자세한 내용은 각 플러그인의 문서를 참조하세요.

자세한 내용은 자바 개발 환경 설정을 참조하세요.

Node.js

npm install --save @google-cloud/vision

자세한 내용은 Node.js 개발 환경 설정을 참조하세요.

PHP

composer require google/apiclient

자세한 내용은 Google Cloud에서 PHP 사용을 참조하세요.

Python

pip install --upgrade google-cloud-vision

자세한 내용은 Python 개발 환경 설정을 참조하세요.

Ruby

gem install google-api-client

자세한 내용은 Ruby 개발 환경 설정을 참조하세요.

인증 설정

Google Cloud API 호출을 인증하기 위해 클라이언트 라이브러리는 애플리케이션 기본 사용자 인증 정보(ADC)를 지원합니다. 라이브러리가 정의된 위치 집합에서 사용자 인증 정보를 찾고 이러한 사용자 인증 정보를 사용하여 API에 대한 요청을 인증합니다. ADC를 사용하면 애플리케이션 코드를 수정할 필요 없이 로컬 개발 또는 프로덕션과 같은 다양한 환경에서 애플리케이션에 사용자 인증 정보를 제공할 수 있습니다.

프로덕션 환경에서 ADC를 설정하는 방법은 서비스와 컨텍스트에 따라 다릅니다. 자세한 내용은 애플리케이션 기본 사용자 인증 정보 설정을 참조하세요.

로컬 개발 환경의 경우 Google 계정과 연결된 사용자 인증 정보를 사용하여 ADC를 설정할 수 있습니다.

  1. gcloud CLI를 설치하고 초기화합니다.

    gcloud CLI를 초기화할 때 애플리케이션에 필요한 리소스에 액세스할 수 있는 권한이 있는 Google Cloud 프로젝트를 지정해야 합니다.

  2. 사용자 인증 정보 파일을 만듭니다.

    gcloud auth application-default login

    로그인 화면이 표시됩니다. 로그인 후 사용자 인증 정보는 ADC에 사용하는 로컬 사용자 인증 정보 파일에 저장됩니다.

클라이언트 라이브러리 사용

다음 예시에서는 클라이언트 라이브러리를 사용하는 방법을 보여줍니다.

C++


#include "google/cloud/vision/v1/image_annotator_client.h"
#include <iostream>

int main(int argc, char* argv[]) try {
  auto constexpr kDefaultUri =
      "gs://cloud-samples-data/vision/label/wakeupcat.jpg";
  if (argc > 2) {
    std::cerr << "Usage: " << argv[0] << " [gcs-uri]\n"
              << "  The gcs-uri must be in gs://... format. It defaults to "
              << kDefaultUri << "\n";
    return 1;
  }
  auto uri = std::string{argc == 2 ? argv[1] : kDefaultUri};

  namespace vision = ::google::cloud::vision_v1;
  auto client =
      vision::ImageAnnotatorClient(vision::MakeImageAnnotatorConnection());

  // Define the image we want to annotate
  google::cloud::vision::v1::Image image;
  image.mutable_source()->set_image_uri(uri);
  // Create a request to annotate this image with Request text annotations for a
  // file stored in GCS.
  google::cloud::vision::v1::AnnotateImageRequest request;
  *request.mutable_image() = std::move(image);
  request.add_features()->set_type(
      google::cloud::vision::v1::Feature::TEXT_DETECTION);

  google::cloud::vision::v1::BatchAnnotateImagesRequest batch_request;
  *batch_request.add_requests() = std::move(request);
  auto batch = client.BatchAnnotateImages(batch_request);
  if (!batch) throw std::move(batch).status();

  // Find the longest annotation and print it
  auto result = std::string{};
  for (auto const& response : batch->responses()) {
    for (auto const& annotation : response.text_annotations()) {
      if (result.size() < annotation.description().size()) {
        result = annotation.description();
      }
    }
  }
  std::cout << "The image contains this text: " << result << "\n";

  return 0;
} catch (google::cloud::Status const& status) {
  std::cerr << "google::cloud::Status thrown: " << status << "\n";
  return 1;
}

Go


// Sample vision-quickstart uses the Google Cloud Vision API to label an image.
package main

import (
	"context"
	"fmt"
	"log"
	"os"

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

func main() {
	ctx := context.Background()

	// Creates a client.
	client, err := vision.NewImageAnnotatorClient(ctx)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}
	defer client.Close()

	// Sets the name of the image file to annotate.
	filename := "../testdata/cat.jpg"

	file, err := os.Open(filename)
	if err != nil {
		log.Fatalf("Failed to read file: %v", err)
	}
	defer file.Close()
	image, err := vision.NewImageFromReader(file)
	if err != nil {
		log.Fatalf("Failed to create image: %v", err)
	}

	labels, err := client.DetectLabels(ctx, image, nil, 10)
	if err != nil {
		log.Fatalf("Failed to detect labels: %v", err)
	}

	fmt.Println("Labels:")
	for _, label := range labels {
		fmt.Println(label.Description)
	}
}

Java

// Imports the Google Cloud client library

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.Feature.Type;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.protobuf.ByteString;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // 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 vision = ImageAnnotatorClient.create()) {

      // The path to the image file to annotate
      String fileName = "./resources/wakeupcat.jpg";

      // Reads the image file into memory
      Path path = Paths.get(fileName);
      byte[] data = Files.readAllBytes(path);
      ByteString imgBytes = ByteString.copyFrom(data);

      // Builds the image annotation request
      List<AnnotateImageRequest> requests = new ArrayList<>();
      Image img = Image.newBuilder().setContent(imgBytes).build();
      Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build();
      AnnotateImageRequest request =
          AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
      requests.add(request);

      // Performs label detection on the image file
      BatchAnnotateImagesResponse response = vision.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 (EntityAnnotation annotation : res.getLabelAnnotationsList()) {
          annotation
              .getAllFields()
              .forEach((k, v) -> System.out.format("%s : %s%n", k, v.toString()));
        }
      }
    }
  }
}

Node.js

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

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

  // Performs label detection on the image file
  const [result] = await client.labelDetection('./resources/wakeupcat.jpg');
  const labels = result.labelAnnotations;
  console.log('Labels:');
  labels.forEach(label => console.log(label.description));
}
quickstart();

Python


# Imports the Google Cloud client library
from google.cloud import vision

def run_quickstart() -> vision.EntityAnnotation:
    """Provides a quick start example for Cloud Vision."""

    # Instantiates a client
    client = vision.ImageAnnotatorClient()

    # The URI of the image file to annotate
    file_uri = "gs://cloud-samples-data/vision/label/wakeupcat.jpg"

    image = vision.Image()
    image.source.image_uri = file_uri

    # Performs label detection on the image file
    response = client.label_detection(image=image)
    labels = response.label_annotations

    print("Labels:")
    for label in labels:
        print(label.description)

    return labels

추가 리소스

C++

다음 목록에는 C++용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

C#

다음 목록에는 C#용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

Go

다음 목록에는 Go용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

Java

다음 목록에는 자바용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

Node.js

다음 목록에는 Node.js용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

PHP

다음 목록에는 PHP용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

Python

다음 목록에는 Python용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

Ruby

다음 목록에는 Ruby용 클라이언트 라이브러리와 관련된 추가 리소스의 링크가 포함되어 있습니다.

추가 클라이언트 라이브러리

위에 나온 라이브러리 외에도 Spring Cloud Google Cloud를 자바 애플리케이션에서 사용할 수 있습니다. Spring Vision API는 Spring Framework로 빌드된 모든 애플리케이션에서 Cloud Vision을 사용할 수 있도록 지원합니다.

시작하려면 애플리케이션에 Spring Cloud Vision을 추가하는 방법을 알아보세요.

직접 사용해 보기

Google Cloud를 처음 사용하는 경우 계정을 만들어 실제 시나리오에서 Cloud Vision API의 성능을 평가할 수 있습니다. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.

Cloud Vision API 무료로 사용해 보기