Google Cloud Vision API sample for python

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

Google Cloud Vision API sample for python
Use Google Cloud Vision API from Python
I tried the Google Cloud Vision API for the first time
Text extraction with GCP Cloud Vision API (Python3.6)
I tried using the Google Cloud Vision API
Tweet (API 1.1) on Google App Engine for Python
Python calling Google Cloud Vision API from LINE BOT via AWS Lambda
[GCP] [Python] Deploy API serverless with Google Cloud Functions!
Speech transcription procedure using Python and Google Cloud Speech API
[Python] Sample code for Python grammar
Google Drive Api Tips (Python)
Sample image of Python API server for EC2 (public AMI)
Try to determine food photos using Google Cloud Vision API
Get data from analytics API with Google API Client for python
[Python] Hit the Google Translation API
[Python3] Google translate google translate without using api
My favorite boto3 (Python) API sample
Use Google Analytics API from Python
Stream speech recognition using Google Cloud Speech gRPC API on python3 on Mac!
Until you try the Google Cloud Vision API (harmful image detection)
Let's touch Google's Vision API from Python for the time being
[SEO] Flow / sample code when using Google Analytics API in Python
[google-oauth] [python] Google APIs Client Library for Python
Streaming speech recognition with Google Cloud Speech API
PHP / Python / Ruby sample hitting Path API
Get Google Fit API data in Python
Try using Python with Google Cloud Functions
Speech transcription procedure using Google Cloud Speech API
[GCP] Operate Google Cloud Storage with Python
Sample for handling eml files in Python
How to use GCP's Cloud Vision API
Creating Google Spreadsheet using Python / Google Data API
Implemented Python wrapper for Qiita API v2
I tried to extract characters from subtitles (OpenCV: Google Cloud Vision API)
When introducing the Google Cloud Vision API to rails, I followed the documentation.
Detect Japanese characters from images using Google's Cloud Vision API in Python
Edit Slide (PowerPoint for Google) with Python (Low-cost RPA case with Google API and Python)
2016-10-30 else for Python3> for:
python [for myself]
Problems with output results with Google's Cloud Vision API
Created a Python wrapper for the Qiita API
Data acquisition from analytics API with Google API Client for python Part 2 Web application
I tried "License OCR" with Google Vision API
Run Google Analytics API (core v3) in python
Python closure sample
Automatic voice transcription with Google Cloud Speech API
Tips for hitting the ATND API in Python
How to use the Google Cloud Translation API
How to use Service Account OAuth and API with Google API Client for python
I tried "Receipt OCR" with Google Vision API
[Google Cloud Platform] Use Google Cloud API using API Client Library
Touch the sample v20-python-samples of the OANDA v20 REST API wrapper library for Python
kabu StationĀ® API --Updated Python wrapper for PUSH API
Get data labels by linking with Google Cloud Vision API when previewing images with Rails
[BigQuery] How to use BigQuery API for Python -Table creation-
Upload JPG file using Google Drive API in Python
Specific sample code for working with SQLite3 in Python
List of sample program distribution sites for python books
From python to running instance on google cloud platform
Explore Alibaba Cloud Function Compute for DevOps using Python 3.0
[Python] Get insight data using Google My Business API