当前位置: 首页 > 知识库问答 >
问题:

索引器:使用谷歌云视觉API的bytearray

广亮
2023-03-14

我正在尝试使用Google Cloud Vision API来检测图像中的文本,我遵循了以下教程中的代码:https://cloud.google.com/vision/docs/fulltext-annotations

完整代码如下:

import argparse
from enum import Enum
import io

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):
    """Draw a border around the image using the hints in the vector list."""
    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):
    """Returns document bounds given an image."""
    client = vision.ImageAnnotatorClient()

    bounds = []

    with io.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):
    image = Image.open(filein)
    bounds = get_document_bounds(filein, FeatureType.BLOCK)
    draw_boxes(image, bounds, 'red')
    bounds = get_document_bounds(filein, FeatureType.PARA)
    draw_boxes(image, bounds, 'red')
    bounds = get_document_bounds(filein, FeatureType.WORD)
    draw_boxes(image, bounds, 'red')

    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 = parser.parse_args()

    render_doc_text(args.detect_file, args.out_file)

我将Windows 10与Python 3.7一起使用,并在命令提示符中使用以下代码:

C:\Users\ariel\Dropbox\Research\Mestizo\Code>python doctext.py censo_19940_tab_corta-30.png -out_file out.jpg

我得到了以下错误和回溯:

Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\lib\site-packages\PIL\ImagePalette.py", line 99, in getcolor
    return self.colors[color]
KeyError: (255, 0, 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "doctext.py", line 96, in <module>
    render_doc_text(args.detect_file, args.out_file)
  File "doctext.py", line 78, in render_doc_text
    draw_boxes(image, bounds, 'red')
  File "doctext.py", line 35, in draw_boxes
    bound.vertices[3].x, bound.vertices[3].y], None, color)
  File "C:\ProgramData\Anaconda3\lib\site-packages\PIL\ImageDraw.py", line 239, in polygon
    ink, fill = self._getink(outline, fill)
  File "C:\ProgramData\Anaconda3\lib\site-packages\PIL\ImageDraw.py", line 113, in _getink
    ink = self.palette.getcolor(ink)
  File "C:\ProgramData\Anaconda3\lib\site-packages\PIL\ImagePalette.py", line 109, in getcolor
    self.palette[index + 256] = color[1]
IndexError: bytearray index out of range

我已经浏览了以前关于这个错误的帖子,但我不知道这是从哪里来的。

共有1个答案

华炜
2023-03-14

问题是,当我应该使用jpg时,我正在使用png文件。代码/教程的留档使用jpg文件作为输入:

https://cloud.google.com/vision/docs/fulltext-annotations

转换成jpg后,代码运行没有问题,并产生了预期的输出。

 类似资料:
  • 我想从谷歌云视觉应用编程接口中获取数据,并看到输入可以以Base64和图像uri格式给出。但是Base64似乎太长了,以uri上传图像需要一些额外的时间。请让我知道,如果有人知道这方面的任何其他工作。

  • 我正在尝试Google Cloud Vision API(测试版),它返回“权限被拒绝”消息。但该项目启用了“云视觉API”。感谢您的帮助。 谷歌API浏览器中的错误详细信息

  • 我正在使用谷歌云视觉应用编程接口来搜索类似的图像(网络检测),它工作得很好。谷歌检测完全匹配的图像和部分匹配的图像(裁剪版本)。 我正在寻找一种方法来检测更多不同的版本。例如,当我寻找一个标志时,我想检测这个标志的大、小、方形、矩形...版本。目前,我检测到与我上传和裁剪版本完全匹配的图像。 你知道这是否可能,我该怎么做?

  • 我是谷歌API的新手。最近,我使用了Google Vision API,但遇到了以下问题: 我尝试了“创建服务帐户”的解决方案,以生成服务json键并在py中调用它。脚本,它将在几乎3~4个url中首先工作,但在下一个url中会出错。这是我的检测代码: 我在另一个py中调用“detect.py”。脚本:

  • 我使用这个API来进行测试https://cloud.google.com/vision/docs/ocr测试引擎。 请求机构: 结果就是 我错过什么了吗?非常感谢。