Search code examples
pythongoogle-cloud-vision

imageUri : path to local file


I am accessing google vision api using requests.post method in python (jupyter notebook)

in imageUri i can only specify weburl or bucket uri. I cannot specify local file name like "/Users/pi/test.jpg"

file_name = '/Users/mbp/Pictures/full moon.jpg'
data = {
  "requests":[
    {
      "image":{
    "source":{
      "imageUri": file_name
    }
  },
  "features":[
    {
      "type":"FACE_DETECTION",
      "maxResults":1
    }
   ]
  }
 ]
}

r = requests.post(url=url,json=data)
x= json.loads(r.text)
print(x['responses'])

response i get is:

[{'error': {'code': 3, 'message': 'image-annotator::Malformed request.: Unsupported URI protocol specified: /Users/mbp/Pictures/full moon.jpg'}}]

please help


Solution

  • For local files you need to load the file content, encode it, and put the encoded image content under the content key. For details, see here. The information about base64 encoding is linked on that page as well.

    Your code can be updated as follows:

    import base64
    
    file_name = '/Users/mbp/Pictures/full moon.jpg'
    with open(file_name, 'r') as image:
        image_content = image.read()
        encoded_content = base64.b64encode(image_content)
    
    data = {
      "requests":[
        {
          "image":{
          "content": encoded_content
        },
      "features":[
        {
          "type":"FACE_DETECTION",
          "maxResults":1
        }
       ]
      }
     ]
    }
    
    r = requests.post(url=url,json=data)
    x = json.loads(r.text)
    print(x['responses'])
    

    Alternatively you might consider using the client libraries; some information here.