Google视觉API无法打印退货

时间:2019-05-08 13:19:22

标签: python google-vision vision-api

我正在使用python中的一些脚本,并试图查找这些图像是否返回结果。但是,当运行python时不会打印任何内容。我没有收到错误,但似乎无法弄清楚。

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

我将这些示例作为工作的基础

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

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

1 个答案:

答案 0 :(得分:0)

您缺少一些关键部分:

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()

在编辑教程脚本时,您需要注意的一些关键问题是跟随对象的。如果您不先创建该对象,则不能在您自己的脚本中使用本教程中调用的对象。