Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save internetmosquito/b1c1f00ac99d9aa1f79cfdc21be36b5b to your computer and use it in GitHub Desktop.
Save internetmosquito/b1c1f00ac99d9aa1f79cfdc21be36b5b to your computer and use it in GitHub Desktop.
How to encode images for Google Cloud Vision
images_names = list()
for iterator, image_file in enumerate(images):
image_path = os.path.join(folder_name, image_file)
images_names.append(self.path_leaf(image_path))
self.images_names.append(self.path_leaf(image_path))
with open(image_path, 'rb') as image:
image_content = base64.b64encode(image.read())
image_payload = {}
image_payload['image'] = {}
image_payload['image']['content'] = image_content.decode('UTF-8')
image_payload['features'] = [{
'type': 'LABEL_DETECTION',
'maxResults': self.MAX_LABELS
}]
payload['requests'].append(image_payload)
# Need to check if we have reached 10 images, meaning we must send a request,
# Google does not like more than 10 images (more or less) per request
if (iterator + 1) % 10 == 0:
try:
response = requests.post(self.google_vision_url, json=payload)
payload = {}
payload['requests'] = []
# response = service_request.execute()
json_response = response.json()
if 'responses' in json_response.keys():
intermediate = json_response['responses']
merged = zip(images_names, intermediate)
response = dict()
response['responses'] = []
for element in merged:
image_labeled = {}
image_labeled[element[0]] = element[1]
response['responses'].append(image_labeled)
responses.append(response)
images_names = list()
# Add one second delay before making another request
time.sleep(5)
except requests.exceptions.RequestException as ex:
print('The following error occurred trying to label images with Google {0}'.format(str(ex)))
continue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment