Search code examples
pythonpython-2.7gcloudgoogle-cloud-vision

Can Google's Vision API accept a URL from any external server and return a response on that image?


I have been able to run Google's Vision API successfully on locally stored images. However, whenever I run my script on an image stored on an external server. I get an error.

import io
import os
from google.cloud import vision

vision_client = vision.Client()
file_name = "https://static.pexels.com/photos/36753/flower-purple-lical-blosso.jpg"

with io.open(file_name, 'rb') as image_file:
    content = image_file.read()
    image = vision_client.image(content=content, )

    labels = image.detect_labels()
    for label in labels:
        print(label.description)

The error says

  Traceback (most recent call last):
  File "visionex.py", line 8, in <module>
    with io.open(file_name, 'rb') as image_file:
  IOError: [Errno 2] No such file or directory: 
 'https://static.pexels.com/photos/36753/flower-purple-lical-blosso.jpg'

Solution

  • You shouldn't use io.open here try using the requests module

    import requests  # the lib that handles the url stuff
    
    data = requests.get(file_name)
    content = data.content
    

    You cant open a remote file using the io.open function. Read more about the requests module to handle requests to remote file.