密集文件文字偵測教學課程

目標對象

本教學課程的目標是協助您使用 Google Cloud Vision API 文件文字偵測功能開發應用程式。本教學課程假設您熟悉基本程式設計結構和技術,但即使您是程式設計新手,也應該能夠輕鬆完成本教學課程,然後使用 Cloud Vision API 參考說明文件建立基本應用程式。

必要條件

使用文件文字 OCR 為圖片加上註解

本教學課程會逐步引導您操作基本的 Vision API 應用程式,該應用程式會發出 DOCUMENT_TEXT_DETECTION 要求,然後處理 fullTextAnnotation 回應

fullTextAnnotation 是從圖片擷取的 UTF-8 文字結構化階層式回應,依序為「頁面」→「區塊」→「段落」→「字詞」→「符號」:

  • Page 是區塊的集合,以及頁面的中繼資訊:大小、解析度 (X 解析度和 Y 解析度可能不同)。

  • Block 代表網頁的「邏輯」元素,例如文字涵蓋的區域,或是欄之間的圖片或分隔符。文字和表格區塊包含擷取文字所需的主要資訊。

  • Paragraph 是文字的結構單元,代表依序排列的字詞。根據預設,系統會將斷字視為字詞分隔符。

  • Word 是最小的文字單位。並以符號陣列表示。

  • Symbol 代表字元或標點符號。

fullTextAnnotation 也可提供網頁圖片的網址,這些圖片與要求中的圖片部分或完全相符。

完整程式碼清單

閱讀程式碼時,建議您一併參閱 Cloud Vision API Python 參考資料

import argparse
from enum import Enum

from google.cloud import vision
from PIL import Image, ImageDraw



class FeatureType(Enum):
    PAGE = 1
    BLOCK = 2
    PARA = 3
    WORD = 4
    SYMBOL = 5


def draw_boxes(image, bounds, color):
    """Draws a border around the image using the hints in the vector list.

    Args:
        image: the input image object.
        bounds: list of coordinates for the boxes.
        color: the color of the box.

    Returns:
        An image with colored bounds added.
    """
    draw = ImageDraw.Draw(image)

    for bound in bounds:
        draw.polygon(
            [
                bound.vertices[0].x,
                bound.vertices[0].y,
                bound.vertices[1].x,
                bound.vertices[1].y,
                bound.vertices[2].x,
                bound.vertices[2].y,
                bound.vertices[3].x,
                bound.vertices[3].y,
            ],
            None,
            color,
        )
    return image


def get_document_bounds(image_file, feature):
    """Finds the document bounds given an image and feature type.

    Args:
        image_file: path to the image file.
        feature: feature type to detect.

    Returns:
        List of coordinates for the corresponding feature type.
    """
    client = vision.ImageAnnotatorClient()

    bounds = []

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

    image = vision.Image(content=content)

    response = client.document_text_detection(image=image)
    document = response.full_text_annotation

    # Collect specified feature bounds by enumerating all document features
    for page in document.pages:
        for block in page.blocks:
            for paragraph in block.paragraphs:
                for word in paragraph.words:
                    for symbol in word.symbols:
                        if feature == FeatureType.SYMBOL:
                            bounds.append(symbol.bounding_box)

                    if feature == FeatureType.WORD:
                        bounds.append(word.bounding_box)

                if feature == FeatureType.PARA:
                    bounds.append(paragraph.bounding_box)

            if feature == FeatureType.BLOCK:
                bounds.append(block.bounding_box)

    # The list `bounds` contains the coordinates of the bounding boxes.
    return bounds




def render_doc_text(filein, fileout):
    """Outlines document features (blocks, paragraphs and words) given an image.

    Args:
        filein: path to the input image.
        fileout: path to the output image.
    """
    image = Image.open(filein)
    bounds = get_document_bounds(filein, FeatureType.BLOCK)
    draw_boxes(image, bounds, "blue")
    bounds = get_document_bounds(filein, FeatureType.PARA)
    draw_boxes(image, bounds, "red")
    bounds = get_document_bounds(filein, FeatureType.WORD)
    draw_boxes(image, bounds, "yellow")

    if fileout != 0:
        image.save(fileout)
    else:
        image.show()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("detect_file", help="The image for text detection.")
    parser.add_argument("-out_file", help="Optional output file", default=0)
    args =