【问题标题】:Format OCR text annotation from Cloud Vision API in Python在 Python 中从 Cloud Vision API 格式化 OCR 文本注释
【发布时间】:2018-01-15 15:59:31
【问题描述】:

我在我正在使用的一个小程序上使用适用于 Python 的 Google Cloud Vision API。该功能正在运行,我得到了 OCR 结果,但我需要先对这些结果进行格式化,然后才能使用它们。

这是函数:

# Call to OCR API
def detect_text_uri(uri):
    """Detects text in the file located in Google Cloud Storage or on the Web.
    """
    client = vision.ImageAnnotatorClient()
    image = types.Image()
    image.source.image_uri = uri

    response = client.text_detection(image=image)
    texts = response.text_annotations

    for text in texts:
        textdescription = ("    "+ text.description )
        return textdescription

我特别需要将文本逐行切片,并在开头添加四个空格,最后添加一个换行符,但此时这仅适用于第一行,其余作为单行返回斑点。

我一直在查看官方文档,但并没有真正了解 API 响应的格式。

【问题讨论】:

    标签: python google-cloud-platform google-cloud-vision


    【解决方案1】:

    你几乎就在那儿。由于您想逐行分割文本,而不是循环文本注释,请尝试从 google vision 的响应中获取直接的“description”,如下所示。

    def parse_image(image_path=None):
        """
        Parse the image using Google Cloud Vision API, Detects "document" features in an image
        :param image_path: path of the image
        :return: text content
        :rtype: str
        """
    
        client = vision.ImageAnnotatorClient()
        response = client.text_detection(image=open(image_path, 'rb'))
        text = response.text_annotations
        del response     # to clean-up the system memory
    
        return text[0].description
    

    上面的函数返回一个带有图片内容的字符串,行之间用“\n”隔开

    现在,您可以根据需要为每一行添加前缀和后缀。

    image_content = parse_image(image_path="path\to\image")
    
    my_formatted_text = ""
    for line in image_content.split("\n"):
        my_formatted_text += "    " + line + "\n"
    

    my_formatted_text 是您需要的文本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-02
      • 2020-08-13
      • 1970-01-01
      • 2018-06-13
      • 1970-01-01
      相关资源
      最近更新 更多