網路偵測教學課程

目標對象

本教學課程的目標是協助您使用 Vision API 網頁偵測功能開發應用程式。本教學課程假設您熟悉基本程式設計結構和技巧,但即使您是初學程式設計,也應該能夠輕鬆跟著操作本教學課程,然後使用 Vision API 參考說明文件建立基本應用程式。

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

必要條件

Python

總覽

本教學課程會逐步引導您操作使用 Web detection 要求的 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 類別,用於存取 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 進行驗證

在與 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

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