Vision APIをサクッと使ってみるコードです。API_KEY
あたりは適当に取得してください
requestsを使います
pip install requests
リクエスト
import base64
import requests
API_KEY = "your api key here"
image_path = "/path/to/image"
image_content = base64.encodebytes(open(image_path, "rb").read()).decode("utf8")
data=json.dumps({
"requests": [{
"image":{
"content": image_content
},
"features":[{
"type": "TEXT_DETECTION",
"maxResults":10
},{
"type": "SAFE_SEARCH_DETECTION",
"maxResults":10
},{
"type": "LOGO_DETECTION",
"maxResults":10
},{
"type": "LABEL_DETECTION",
"maxResults":10
}]
}]
})
response = requests.post(
url='https://vision.googleapis.com/v1/images:annotate?key='+API_KEY,
data=data,
headers={'Content-Type': 'application/json'}
)
print(response.text)
requests
の中に、Array
でいれることができるので、複数の画像を同時にリクエストすることが可能です。features
に関しても同様です。maxResults
は結果の最大数ですね
結果
自分のアイコンでやってみた結果がこちら。
{
"responses": [
{
"labelAnnotations": [
{
"mid": "/m/0jg24",
"description": "image",
"score": 0.90161264
},
{
"mid": "/m/0c9ph5",
"description": "flower",
"score": 0.7957691
},
{
"mid": "/m/05qdh",
"description": "painting",
"score": 0.7040579
},
{
"mid": "/m/0jjw",
"description": "art",
"score": 0.69042236
},
{
"mid": "/m/067408",
"description": "album cover",
"score": 0.68407893
},
{
"mid": "/m/0b0fq",
"description": "photomontage",
"score": 0.6226878
},
{
"mid": "/m/015r61",
"description": "modern art",
"score": 0.5952117
},
{
"mid": "/m/01bsxb",
"description": "collage",
"score": 0.5079488
}
],
"textAnnotations": [
{
"locale": "ko",
"description": "T\u003e\n냐\n",
"boundingPoly": {
"vertices": [
{
"x": 108,
"y": 73
},
{
"x": 361,
"y": 73
},
{
"x": 361,
"y": 277
},
{
"x": 108,
"y": 277
}
]
}
},
{
"description": "T",
"boundingPoly": {
"vertices": [
{
"x": 362,
"y": 73
},
{
"x": 362,
"y": 82
},
{
"x": 353,
"y": 82
},
{
"x": 353,
"y": 73
}
]
}
},
{
"description": "\u003e",
"boundingPoly": {
"vertices": [
{
"x": 352,
"y": 73
},
{
"x": 352,
"y": 82
},
{
"x": 343,
"y": 82
},
{
"x": 343,
"y": 73
}
]
}
},
{
"description": "냐",
"boundingPoly": {
"vertices": [
{
"x": 118,
"y": 269
},
{
"x": 116,
"y": 277
},
{
"x": 109,
"y": 274
},
{
"x": 111,
"y": 267
}
]
}
}
],
"safeSearchAnnotation": {
"adult": "VERY_UNLIKELY",
"spoof": "UNLIKELY",
"medical": "VERY_UNLIKELY",
"violence": "UNLIKELY"
}
}
]
}
LOGO_DETECTION
はなかったみたいなので、返ってきてませんね