This article is a sample code and explanation for using the Google Cloud Vision API. This sample code is supposed to be used by importing with other python code.
If you want to check the operation by itself, uncomment the part below ## main and perform the unit test.
First of all, you need to get the API key of the Google Cloud Vision API in order to run this sample. Also, save the sample image you want to analyze as data / sample.png in the same hierarchy as the program to be prepared and executed in advance.
When this code is executed, the image data will be sent to the Google Cloud Vision API, the returned result will be displayed on the screen, and the description value will be saved in tmp.
As an application, you can check if the difference has occurred by returning True only if the JSON value returned by the update_json_file method is different. With this value, you can use it as a bot and mutter like twitter, line, or slack.
googlecv.py
# -*- coding: utf-8 -*-
import requests
import json
import base64
import os
GOOGLE_CLOUD_VISION_API_URL = 'https://vision.googleapis.com/v1/images:annotate?key='
API_KEY = 'YOUR-GOOGLE-CLOUD-VISION-API-KEY'
def goog_cloud_vison (image_content):
api_url = GOOGLE_CLOUD_VISION_API_URL + API_KEY
req_body = json.dumps({
'requests': [{
'image': {
'content': image_content
},
'features': [{
'type': 'LABEL_DETECTION',
'maxResults': 10,
}]
}]
})
res = requests.post(api_url, data=req_body)
return res.json()
def img_to_base64(filepath):
with open(filepath, 'rb') as img:
img_byte = img.read()
return base64.b64encode(img_byte)
def get_descs_from_return(res_json):
labels = res_json['responses'][0]['labelAnnotations']
descs = []
for value in labels:
descs.append(value['description'])
return json.dumps(descs)
def update_json_file(json_desc):
fname = '/tmp/descs.json'
if os.path.isfile(fname)==True:
with open('/tmp/descs.json', 'r') as f:
f_desc = json.load(f)
else:
f_desc = ''
if json_desc != f_desc:
with open('/tmp/descs.json', 'w') as f:
json.dump(json_desc, f, sort_keys=True, indent=4)
return True
else:
return False
##
## main
##
#dir = os.path.dirname(os.path.abspath(__file__))
#filename = os.path.join(dir, 'data', 'sample.png')
#print filename
#img = img_to_base64(filename)
#res_json = goog_cloud_vison(img)
#json_desc = get_descs_from_return(res_json)
#print json_desc
#update_json_file(json_desc)
Recommended Posts