ספריות לקוח של Vision

בדף הזה מוסבר איך להתחיל להשתמש בספריות הלקוח של Cloud עבור Vision API. ספריות לקוח מאפשרות לגשת בקלות ל-Google Cloud APIs בשפה נתמכת. אמנם אפשר להשתמש ישירות ב-Google Cloud APIs על ידי יצירת בקשות גולמיות חדשות לשרת, אבל ספריות לקוח מפשטות את התהליך ומפחיתות באופן משמעותי את כמות הקוד שתצטרכו לכתוב.

מידע נוסף על ספריות הלקוח ב-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

If you are using Maven, add the following to your pom.xml file. For more information about BOMs, see The Google Cloud Platform Libraries BOM.

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

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

If you are using Gradle, add the following to your dependencies:

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

If you are using sbt, add the following to your dependencies:

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

If you're using Visual Studio Code or IntelliJ, you can add client libraries to your project using the following IDE plugins:

The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.

מידע נוסף זמין במאמר הגדרת סביבת פיתוח בשפת Java.

Node.js

npm install @google-cloud/vision

מידע נוסף זמין במאמר הגדרת סביבת פיתוח ב-Node.js.

PHP

composer require google/apiclient

מידע נוסף זמין במאמר שימוש ב-PHP ב-Google Cloud.

Python

pip install --upgrade google-cloud-vision

מידע נוסף מופיע במאמר הגדרת סביבת פיתוח בשפת Python.

Ruby

gem install google-api-client

מידע נוסף זמין במאמר הגדרת סביבת פיתוח בשפת Ruby.

מגדירים אימות

כדי לאמת קריאות לממשקי ה-API של Google Cloud , ספריות הלקוח תומכות ב-Application Default Credentials ‏ (ADC). בספריות מתבצע חיפוש של פרטי כניסה בקבוצה של מיקומים מוגדרים, והמערכת משתמשת בפרטי הכניסה האלה כדי לאמת בקשות ל-API. בעזרת ADC, פרטי הכניסה לאפליקציה יכולים להיות זמינים בסביבות שונות, כמו בפיתוח מקומי או בייצור, בלי שיהיה צריך לשנות את קוד האפליקציה.

בסביבות ייצור, אופן ההגדרה של ADC תלוי בשירות ובהקשר. מידע נוסף זמין במאמר בנושא הגדרה של Application Default Credentials.

בסביבת פיתוח מקומית, אפשר להגדיר את ADC עם פרטי הכניסה שמשויכים לחשבון Google שלכם:

  1. Install the Google Cloud CLI. After installation, initialize the Google Cloud CLI by running the following command:

    gcloud init

    If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  2. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    מסך הכניסה יופיע. אחרי שנכנסים, פרטי הכניסה נשמרים בקובץ פרטי הכניסה המקומי שמשמש את 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

ברשימה הבאה מופיעים קישורים למקורות מידע נוספים שקשורים לספריית הלקוח של Java:

Node.js

ברשימה הבאה מופיעים קישורים למקורות מידע נוספים שקשורים לספריית הלקוח של Node.js:

PHP

ברשימה הבאה מופיעים קישורים למקורות מידע נוספים שקשורים לספריית הלקוח של PHP:

Python

ברשימה הבאה מופיעים קישורים למקורות מידע נוספים שקשורים לספריית הלקוח של Python:

Ruby

ברשימה הבאה מופיעים קישורים למקורות מידע נוספים שקשורים לספריית הלקוח של Ruby:

ספריות לקוח נוספות

בנוסף לספריות שמוצגות למעלה, Spring Cloud Google Cloud זמינה לאפליקציות Java. ‫Spring Vision API עוזר לכם להשתמש ב-Cloud Vision בכל אפליקציה שנבנתה באמצעות Spring Framework.

כדי להתחיל, מומלץ לקרוא על הוספת Spring Cloud Vision לאפליקציה.

נסו בעצמכם

אנחנו ממליצים למשתמשים חדשים ב-Google Cloud ליצור חשבון כדי שיוכלו להעריך את הביצועים של Cloud Vision API בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300 $להרצה, לבדיקה ולפריסה של עומסי העבודה.

ניסיון חינם של Cloud Vision API