網路偵測教學課程

本教學課程說明如何在 Python 應用程式中使用 Vision API 網路偵測功能,辨識網路實體、有相符圖像的網頁和類似圖片。

目標對象

本教學課程旨在協助您使用 Vision API 網頁偵測功能開發應用程式。本教學課程假設您熟悉基本的程式設計結構和技術,但即使您是程式設計初學者,也應該能順利完成並執行本教學課程,然後使用 Vision API 參考文件建立基本應用程式。

本教學課程會逐步介紹 Cloud Vision API 應用程式,說明如何呼叫 Cloud Vision API,以使用其網路偵測功能。

必要條件

Python

總覽

本教學課程將逐步引導您瞭解使用 Web detection 要求的基本 Cloud Vision API 應用程式。Web detection 回應會使用下列項目,為要求中傳送的圖片加上註解:

  • 從網路取得的標籤
  • 含有相符圖片的網站網址
  • 與要求中的圖片部分或完全相符的網頁圖片網址
  • 視覺上相似圖片的網址

程式碼清單

閱讀程式碼時,建議您參考 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 用戶端執行網路偵測
  • 迴圈處理回應並輸出結果
  • 列印網路實體清單,並附上說明和分數
  • 列印有相符圖像的網頁清單
  • 列印部分相符的映像檔清單
  • 列印完全相符的圖片清單

詳細說明

以下各節將詳細說明範例應用程式的主要元件。

匯入程式庫

import argparse

from google.cloud import vision

匯入標準程式庫:

  • argparse,讓應用程式接受輸入檔案名稱做為引數
  • io:用於讀取檔案

其他匯入項目:

  • google.cloud.vision 程式庫中的 ImageAnnotatorClient 類別,用於存取 Cloud Vision API。
  • google.cloud.vision 程式庫中的 types 模組,用於建構要求。

執行應用程式

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() 函式。

向 API 進行驗證

與 Cloud Vision API 服務通訊前,您必須使用先前取得的憑證驗證服務。如要在應用程式中取得憑證,最簡單的方式是使用應用程式預設憑證 (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

Cloud Vision API 服務已準備就緒,現在可以建構服務要求。

這個程式碼片段會執行下列工作:

  1. 建立 ImageAnnotatorClient 例項做為用戶端。
  2. 從本機檔案或 URI 建構 Image 物件。
  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,並列印註解中包含的實體和網址 (下一節會顯示每種註解類型的前兩個結果)。

執行應用程式

如要執行應用程式,請傳入下列汽車圖片的網址 (http://www.photos-public-domain.com/wp-content/uploads/2011/01/old-vw-bug-and-van.jpg)。

以下是 Python 指令,其中包含傳入的汽車圖片網址,後面接著控制台輸出內容。請注意,列出的實體後方會加上關聯性分數。請注意,分數不會正規化,也無法在不同的圖片查詢之間比較。

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 執行網路偵測!