מדריך לזיהוי באינטרנט

קהל

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

במדריך הזה נסביר איך ליצור אפליקציה ל-Vision API כדי להשתמש בתכונה לזיהוי אינטרנט.

דרישות מוקדמות

Python

סקירה כללית

במדריך הזה מוסבר איך ליצור אפליקציה בסיסית של Vision API שמשתמשת בWeb detection בקשה. Web detection תשובה מוסיפה הערות לתמונה שנשלחה בבקשה עם:

  • תוויות שהתקבלו מהאינטרנט
  • כתובות URL של אתרים שכוללות תמונות תואמות
  • כתובות URL של תמונות באינטרנט שתואמות באופן חלקי או מלא לתמונה שבבקשה
  • כתובות URL של תמונות דומות

רשימת קוד

במהלך קריאת הקוד, מומלץ לעיין בהפניה ל-Vision API Python.

import argparse

from google.cloud import vision



def annotate(path: str) -> vision.WebDetection:
    """Returns web annotations given the path to an image.

    Args:
        path: path to the input image.

    Returns:
        An WebDetection object with relevant information of the
        image from the internet (i.e., the annotations).
    """
    client = vision.ImageAnnotatorClient()

    if path.startswith("http") or path.startswith("gs:"):
        image = vision.Image()
        image.source.image_uri = path

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

        image = vision.Image(content=content)

    web_detection = client.web_detection(image=image).web_detection

    return web_detection


def report(annotations: vision.WebDetection) -> None:
    """Prints detected features in the provided web annotations.

    Args:
        annotations: The web annotations (WebDetection object) from which
        the features should be parsed and printed.
    """
    if annotations.pages_with_matching_images:
        print(
            f"\n{len(annotations.pages_with_matching_images)} Pages with matching images retrieved"
        )

        for page in annotations.pages_with_matching_images:
            print(f"Url   : {page.url}")

    if annotations.full_matching_images:
        print(f"\n{len(annotations.full_matching_images)} Full Matches found: ")

        for image in annotations.full_matching_images:
            print(f"Url  : {image.url}")

    if annotations.partial_matching_images:
        print(f"\n{len(annotations.partial_matching_images)} Partial Matches found: ")

        for image in annotations.partial_matching_images:
            print(f"Url  : {image.url}")

    if annotations.web_entities:
        print(f"\n{len(annotations.web_entities)} Web entities found: ")

        for entity in annotations.web_entities:
            print(f"Score      : {entity.score}")
            print(f"Description: {entity.description}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    path_help = str(
        "The image to detect, can be web URI, "
        "Google Cloud Storage, or path to local file."
    )
    parser.add_argument("image_url", help=path_help)
    args = parser.parse_args()

    report(annotate(args.image_url))

האפליקציה הפשוטה הזו מבצעת את המשימות הבאות:

  • מייבא את הספריות שנדרשות להרצת האפליקציה
  • מקבל נתיב תמונה כארגומנט ומעביר אותו לפונקציה main()
  • שימוש ב-Google Cloud API Client כדי לבצע זיהוי באינטרנט
  • מבצע לולאה על התגובה ומדפיס את התוצאות
  • מדפיס רשימה של ישויות באינטרנט עם תיאור וציון
  • מדפיס רשימה של דפים תואמים
  • הדפסה של רשימת תמונות עם התאמה חלקית
  • הדפסת רשימה של תמונות שתואמות באופן מלא

מבט מקרוב

ייבוא ספריות

import argparse

from google.cloud import vision

אנחנו מייבאים ספריות רגילות:

  • argparse כדי לאפשר לאפליקציה לקבל שמות של קובצי קלט כארגומנטים
  • io לקריאה מקבצים

ייבוא אחר:

  • המחלקות ImageAnnotatorClient בספרייה google.cloud.vision לגישה ל-Vision API.
  • מודול types בספרייה google.cloud.vision ליצירת בקשות.

הפעלת האפליקציה

parser = argparse.ArgumentParser(
    description=__doc__,
    formatter_class=argparse.RawDescriptionHelpFormatter,
)
path_help = str(
    "The image to detect, can be web URI, "
    "Google Cloud Storage, or path to local file."
)
parser.add_argument("image_url", help=path_help)
args = parser.parse_args()

report(annotate(args.image_url))

כאן אנחנו פשוט מנתחים את הארגומנט שהועבר ומציין את כתובת ה-URL של תמונת האינטרנט, ומעבירים אותו לפונקציה main().

אימות ל-API

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

יצירת הבקשה

client = vision.ImageAnnotatorClient()

if path.startswith("http") or path.startswith("gs:"):
    image = vision.Image()
    image.source.image_uri = path

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

    image = vision.Image(content=content)

web_detection = client.web_detection(image=image).web_detection

עכשיו, אחרי שהשירות Vision API מוכן, אפשר ליצור בקשה לשירות.

קטע הקוד הזה מבצע את המשימות הבאות:

  1. יוצרת מופע ImageAnnotatorClient כלקוח.
  2. יוצר אובייקט Image מקובץ מקומי או מ-URI.
  3. מעבירה את האובייקט Image אל השיטה web_detection של הלקוח.
  4. מחזירה את ההערות.

הדפסת התשובה

if annotations.pages_with_matching_images:
    print(
        f"\n{len(annotations.pages_with_matching_images)} Pages with matching images retrieved"
    )

    for page in annotations.pages_with_matching_images:
        print(f"Url   : {page.url}")

if annotations.full_matching_images:
    print(f"\n{len(annotations.full_matching_images)} Full Matches found: ")

    for image in annotations.full_matching_images:
        print(f"Url  : {image.url}")

if annotations.partial_matching_images:
    print(f"\n{len(annotations.partial_matching_images)} Partial Matches found: ")

    for image in annotations.partial_matching_images:
        print(f"Url  : {image.url}")

if annotations.web_entities:
    print(f"\n{len(annotations.web_entities)} Web entities found: ")

    for entity in annotations.web_entities:
        print(f"Score      : {entity.score}")
        print(f"Description: {entity.description}")

אחרי שהפעולה מסתיימת, אנחנו עוברים על WebDetection ומדפיסים את הישויות וכתובות ה-URL שכלולות בהערה (שני התוצאות הראשונות מכל סוג הערה מוצגות בקטע הבא).

הפעלת האפליקציה

כדי להפעיל את האפליקציה, מעבירים את כתובת ה-URL של האינטרנט (http://www.photos-public-domain.com/wp-content/uploads/2011/01/old-vw-bug-and-van.jpg) של תמונת המכונית הבאה.

זוהי פקודת Python עם כתובת ה-URL של תמונת המכונית באינטרנט, ואחריה פלט המסוף. שימו לב: ציון הרלוונטיות מתווסף אחרי הישויות שמופיעות ברשימה. חשוב לזכור שהציונים לא עוברים נרמול ולא ניתן להשוות אותם בין שאילתות שונות של תמונות.

python web_detect.py "http://www.photos-public-domain.com/wp-content/uploads/2011/01/old-vw-bug-and-van.jpg"
5 Pages with matching images retrieved
Url   : http://www.photos-public-domain.com/2011/01/07/old-volkswagen-bug-and-van/
Url   : http://pix-hd.com/old+volkswagen+van+for+sale
...

2 Full Matches found:
Url  : http://www.photos-public-domain.com/wp-content/uploads/2011/01/old-vw-bug-and-van.jpg
Url  : http://www.wbwagen.com/media/old-volkswagen-bug-and-van-picture-free-photograph-photos-public_s_66f487042adad5a6.jpg

4 Partial Matches found:
Url  : http://www.photos-public-domain.com/wp-content/uploads/2011/01/old-vw-bug-and-van.jpg
Url  : http://www.wbwagen.com/media/old-vw-bug-and-vanjpg_s_ac343d7f041b5f8d.jpg
...

5 Web entities found:
Score      : 5.35028934479
Description: Volkswagen Beetle
Score      : 1.43998003006
Description: Volkswagen
Score      : 0.828279972076
Description: Volkswagen Type 2
Score      : 0.75271999836
Description: Van
Score      : 0.690039992332
Description: Car

כל הכבוד! ביצעתם זיהוי אינטרנט באמצעות Vision API.