"AttributeError: module'google.cloud.vision' has no attribute'types'" in Cloud Vision API (GCP vision AI)

Overview

When I was running the tutorial of GCP object detection API [^ 1], an error occurred, so I wrote a solution. API authentication method is omitted. The language used is Python.

About the error

When I execute the following code in the tutorial, AttributeError occurs. (The code below is copied and pasted from the tutorial)

def localize_objects(path):
    from google.cloud import vision
    client = vision.ImageAnnotatorClient()

    with open(path, 'rb') as image_file:
        content = image_file.read()
    image = vision.types.Image(content=content)

    objects = client.object_localization(
        image=image).localized_object_annotations

    print('Number of objects found: {}'.format(len(objects)))
    for object_ in objects:
        print('\n{} (confidence: {})'.format(object_.name, object_.score))
        print('Normalized bounding polygon vertices: ')
        for vertex in object_.bounding_poly.normalized_vertices:
            print(' - ({}, {})'.format(vertex.x, vertex.y))

The details of the error are as follows. It occurs on the 7th line. It seems that types have been deleted from google.cloud.vision, so an error occurs.

AttributeError: module 'google.cloud.vision' has no attribute 'types'

solution

OK if you use Image directly from vision

image = vision.types.Image(content=content) #error
image = vision.Image(content=content) #Solution

The whole picture is as follows, only the 7th line has been changed

    """Localize objects in the local image.

    Args:
    path: The path to the local file.
    """
    from google.cloud import vision
    client = vision.ImageAnnotatorClient()

    with open(uri, 'rb') as image_file:
        content = image_file.read()
    image = vision.Image(content=content)

    objects = client.object_localization(
        image=image).localized_object_annotations

    print('Number of objects found: {}'.format(len(objects)))
    for object_ in objects:
        print('\n{} (confidence: {})'.format(object_.name, object_.score))
        print('Normalized bounding polygon vertices: ')
        for vertex in object_.bounding_poly.normalized_vertices:
            print(' - ({}, {})'.format(vertex.x, vertex.y))

Digression

The official tutorial has some bugs, isn't it? It doesn't matter, but GCP's Image is a little difficult to use because it's covered with Pillow's Image.

Recommended Posts

"AttributeError: module'google.cloud.vision' has no attribute'types'" in Cloud Vision API (GCP vision AI)
Text extraction with GCP Cloud Vision API (Python3.6)
Flow of extracting text in PDF with Cloud Vision API
Detect Japanese characters from images using Google's Cloud Vision API in Python