pythongoogle-visionvision-api

Google vision API not printing a return


I'm playing around with some scripts in python and trying to find if these image returns results. However when running python doesn't print anything. I don't get an error but can't seem to figure it out.

import io
import os

# Imports the Google Cloud client library
from google.cloud import vision
from google.cloud.vision import types

def run(annotations):
# Instantiates a client
    client = vision.ImageAnnotatorClient()

# The name of the image file to annotate
    file_name = os.path.join(
        os.path.dirname(__file__),
        'static/123456.jpg')

# Loads the image into memory
    with io.open(file_name, 'rb') as image_file:
        content = image_file.read()

        image = types.Image(content=content)

    if annotations.pages_with_matching_images:
        print('\n{} Pages with matching images retrieved'.format(
            len(annotations.pages_with_matching_images)))


    matching = annotations.pages_with_matching_images


        print matching

I'm basing the work on these examples

https://cloud.google.com/vision/docs/quickstart-client-libraries#client-libraries-install-python

https://cloud.google.com/vision/docs/internet-detection


Solution

  • You are missing some key parts:

    import io
    import os
    
    # Imports the Google Cloud client library
    from google.cloud import vision
    from google.cloud.vision import types
    
    def run():   # remove the argument since you aren't using it
    # Instantiates a client
        client = vision.ImageAnnotatorClient()
    
    # The name of the image file to annotate
        file_name = os.path.join(
            os.path.dirname(__file__),
            'static/123456.jpg')
    
    # Loads the image into memory
        with io.open(file_name, 'rb') as image_file:
            content = image_file.read()
    
        image = types.Image(content=content)   # dedent this
    
        web_detection = client.web_detection(image=image).web_detection
    
        """ annotations doesn't exist in your script as is...
        if annotations.pages_with_matching_images:
            print('\n{} Pages with matching images retrieved'.format(
                len(annotations.pages_with_matching_images)))
        """
        # replace above with this
        if web_detection.pages_with_matching_images:
            print('\n{} Pages with matching images retrieved'.format(
                   len(web_detection.pages_with_matching_images)))
    
    if __name__ == '__main__':
        run()
    

    Some of the key issues you need to watch out for when editing tutorial scripts is following your objects along. You can't use an object that is called in the tutorial in your own script if you don't first create that object.