使用googleapiclient将图像文件注释为文本

时间:2018-04-06 01:48:34

标签: python google-cloud-vision

我正在尝试使用Google云端服务注释本地图像文件。我按照此处提供的说明https://cloud.google.com/natural-language/docs/reference/libraries,设置了google API。页面上给出的测试示例执行没有任何问题。但是,当我试图实际注释文件时,我收到错误,这是我正在使用的代码:

files = [];
files.append("/opt/lampp/htdocs/test.jpg");

def get_text_from_files(fileNames):
    texts = detect_text(fileNames);

def detect_text(fileNames):
    max_results = 6;
    num_retries=3;
    service = googleapiclient.discovery.build('language', 'v1');
    batch_request = [];
    for filename in fileNames:
        request = {
            'image': {},
            'features': [{
                'type': 'TEXT_DETECTION',
                'maxResults': max_results,
            }]
        }

        with open(filename, 'rb') as image_file:
            request['image']['content'] = base64.b64encode(image_file.read()).decode('UTF-8');
        batch_request.append(request);

    request = service.images().annotate(body={'requests': batch_request});

    try:
        responses = request.execute(num_retries=num_retries)
        if 'responses' not in responses:
            return {};

        text_response = {};
        for filename, response in zip(
                input_filenames, responses['responses']):

            if 'error' in response:
                logging.error('API Error for {}: {}'.format(
                    filename,
                    response['error'].get('message', '')))
                continue

            text_response[filename] = response.get('textAnnotations', [])

        return text_response;

    except googleapiclient.errors.HttpError as e:
        print ('Http Error for {}: {}', e)
    except KeyError as e2:
        print ('Key error: {}', e2)


get_text_from_files(files);

但我收到错误,我已经给出了下面的堆栈跟踪:

Traceback (most recent call last):
  File "test.py", line 68, in <module>
    get_text_from_files(pdf);
  File "test.py", line 21, in get_text_from_files
    texts = detect_text(fileNames);
  File "test.py", line 41, in detect_text
    request = service.images().annotate(body={'requests': batch_request});
AttributeError: 'Resource' object has no attribute 'images'

提前致谢。

1 个答案:

答案 0 :(得分:0)

请注意,您使用的是错误的Google API客户端Python库。您使用的是Natural Language API,而您要使用的是Vision API。错误消息AttributeError: 'Resource' object has no attribute 'images'表示与Language API关联的资源没有任何images属性。为了解决这个问题,应该做以下更改:

# Wrong API being used
service = googleapiclient.discovery.build('language', 'v1');
# Correct API being used
service = googleapiclient.discovery.build('vision', 'v1');

在此Google API客户端库页面中,您会看到the whole list of available APIs及其名称和版本。在这里,有complete documentation for the Vision API legacy API Client Library

最后,我建议您使用idiomatic Client Libraries而不是旧版API客户端库。它们使用起来更直观,their GitHub page中有一些很好的文档参考。