זיהוי תוויות

‫Vision API יכול לזהות ולחלץ מידע על ישויות בתמונה, במגוון רחב של קטגוריות.

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

התוויות מוחזרות באנגלית בלבד. ‫Cloud Translation API יכול לתרגם תוויות באנגלית לכל אחת משפות אחרות.

תמונה של רחוב במחוז סטאגאיה
קרדיט על התמונה: Alex Knight ב-Unsplash.

לדוגמה, התמונה שלמעלה עשויה להחזיר את רשימת התוויות הבאה:

תיאור Score
רחוב 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 .

ה-method של ה-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 כוללת את התוויות שזוהו, הניקוד שלהן, הרלוונטיות שלהן לנושא ומזהה תוויות אטום, כאשר:

  • mid – אם קיים, מכיל מזהה שנוצר על ידי מכונה (MID) שמתאים לרשומה של הישות ב-Knowledge Graph של Google. שימו לב שהערכים של 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

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Goהוראות ההגדרה שבמדריך לתחילת העבודה עם Vision באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Vision Go API.

כדי לבצע אימות ב-Vision, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


// 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

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Java במאמר התחלת העבודה עם Vision API באמצעות ספריות לקוח. מידע נוסף מופיע ב מאמרי העזרה של Vision API Java.


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

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Node.jsהוראות ההגדרה שבמדריך לתחילת העבודה עם Vision באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Vision Node.js API.

כדי לבצע אימות ב-Vision, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// 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

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Pythonהוראות ההגדרה שבמדריך לתחילת העבודה עם Vision באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Vision Python API.

כדי לבצע אימות ב-Vision, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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# ‎ בדף של ספריות הלקוח ואז עוברים אל מאמרי העזרה בנושא Vision ל-‎ .NET.

PHP: Please follow the PHP setup instructions on the client libraries page and then visit the מאמרי עזרה של Vision עבור PHP.

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

זיהוי תוויות בתמונה מרוחקת

אתם יכולים להשתמש ב-Vision API כדי לבצע זיהוי תכונות בקובץ תמונה מרוחק שנמצא ב-Cloud Storage או באינטרנט. כדי לשלוח בקשה לקובץ מרוחק, מציינים את כתובת ה-URL של הקובץ או את ה-URI של Cloud Storage בגוף הבקשה.

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 .

ה-method של ה-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 כוללת את התוויות שזוהו, הניקוד שלהן, הרלוונטיות שלהן לנושא ומזהה תוויות אטום, כאשר:

  • mid – אם קיים, מכיל מזהה שנוצר על ידי מכונה (MID) שמתאים לרשומה של הישות ב-Knowledge Graph של Google. שימו לב שהערכים של 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

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Goהוראות ההגדרה שבמדריך לתחילת העבודה עם Vision באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Vision Go API.

כדי לבצע אימות ב-Vision, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


// 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

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Java במאמר התחלת העבודה עם Vision API באמצעות ספריות לקוח. מידע נוסף מופיע ב מאמרי העזרה של Vision API Java.


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

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Node.jsהוראות ההגדרה שבמדריך לתחילת העבודה עם Vision באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Vision Node.js API.

כדי לבצע אימות ב-Vision, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// 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

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי Pythonהוראות ההגדרה שבמדריך לתחילת העבודה עם Vision באמצעות ספריות לקוח. מידע נוסף מופיע במאמרי העזרה של Vision Python API.

כדי לבצע אימות ב-Vision, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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# ‎ בדף של ספריות הלקוח ואז עוברים אל מאמרי העזרה בנושא Vision ל-‎ .NET.

PHP: Please follow the PHP setup instructions on the client libraries page and then visit the מאמרי עזרה של Vision עבור PHP.

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

אני רוצה לנסות

אפשר לנסות לזהות תוויות בהמשך. אתם יכולים להשתמש בתמונה שכבר צוינה (gs://cloud-samples-data/vision/label/setagaya.jpeg) או לציין תמונה משלכם במקומה. לוחצים על Execute (הפעלה) כדי לשלוח את הבקשה.

תמונה של רחוב במחוז סטאגאיה
קרדיט על התמונה: Alex Knight ב-Unsplash.

גוף הבקשה:

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

פותחים את Google APIs Explorer ושולחים את הבקשה.

  1. כדי לפתוח את Google APIs Explorer, לוחצים על Try it!‎.

  2. זה שינוי אופציונלי. משנים את גוף הבקשה הקיים.

  3. כדי לשלוח את הבקשה, לוחצים על Execute (ביצוע).