RaspberryPiのカメラモジュールを使って物体認識[Google Cloud Vison API]

前回RaspberryPiを設定した。
今回は,カメラモジュールがあるので遊んでみよう!
Google Cloud Vison APIも使ってみるよ!

目次

サーボモータの組み立て・制御

今回使うのは2軸サーボモータ付きカメラモジュール。
まずは参考サイトを元に組み立て。
パーツを加工しないといけないんで,結構大変。。。

参考サイト:Raspberry Piでサーボコントロール、Part1 上下・左右の2軸を動かす

制御は以下Pythonコードで動かす。
サーボモータから出ている線は,茶色がグランド,赤が+5V,オレンジが角度制御のパルス入力となっている。
コード例はパルス入力をGPIO18にして,基準位置0°に移動させた場合である。

1
2
3
import pigpio
pi = pigpio.pi()
pi.set_servo_pulsewidth(18, 1500) # 0°

パルス幅 1500±1000±90°に相当するので,set_servo_pulsewidth()の第二引数を指定角度になるようにいい感じにすればだいたいOK。
pigpioを使うためにはraspi-cofigでGPIO Serverの設定をenableにしておかないといけないので注意。

参考サイト:

カメラ設定

接続

カメラモジュールから出ているビロビロの紙を,Raspberry PiのCameraって書いてあるところに差し込めばOK

撮影

Raspberry Pi用のコンフィグレーション設定でcameraの項目をenableにしておく。
すると例えば以下コマンドでJpeg形式での画像出力ができる。

1
raspistill -o XXX.jpg

参考サイト:Raspberry Piカメラのセットアップ方法

Pythonで実行するならPicameraを使って以下のような感じ。

1
2
3
4
5
6
7
8
import time
import picamera

with picamera.PiCamera() as camera:
camera.resolution = (1024, 768)
camera.start_preview()
time.sleep(2) # Camera warm-up time
camera.capture('XXX.jpg')

Google Cloud Vison API

Google Cloud Vison APIと連携して,物体認識をさせてみる!

Google Cloud Vison APIを試してみる

参考サイトの通りで何の問題もなく試せた!
結果は以下の通り。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
{
"responses": [
{
"labelAnnotations": [
{
"mid": "/m/07030",
"description": "sushi",
"score": 0.92776537
},
{
"mid": "/m/01ykh",
"description": "cuisine",
"score": 0.9246763
},
{
"mid": "/m/02wbm",
"description": "food",
"score": 0.8793672
},
{
"mid": "/m/042ck",
"description": "japanese cuisine",
"score": 0.8677386
},
{
"mid": "/m/01r1z5",
"description": "asian food",
"score": 0.78632426
}
]
}
]
}
  • ビール
    https://goo.gl/images/CRZvLF
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    {
    "responses": [
    {
    "labelAnnotations": [
    {
    "mid": "/m/0271t",
    "description": "drink",
    "score": 0.9639965
    },
    {
    "mid": "/m/01599",
    "description": "beer",
    "score": 0.85104644
    },
    {
    "mid": "/m/012mj",
    "description": "alcoholic beverage",
    "score": 0.8178871
    },
    {
    "mid": "/m/01z1kdw",
    "description": "juice",
    "score": 0.70181847
    },
    {
    "mid": "/m/024g6",
    "description": "cocktail",
    "score": 0.6707136
    }
    ]
    }
    ]
    }
  • 餃子
    https://goo.gl/images/9JP87L
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    {
    "responses": [
    {
    "labelAnnotations": [
    {
    "mid": "/m/02q08p0",
    "description": "dish",
    "score": 0.9605164
    },
    {
    "mid": "/m/027wmf",
    "description": "jiaozi",
    "score": 0.8821132
    },
    {
    "mid": "/m/01ykh",
    "description": "cuisine",
    "score": 0.8263993
    },
    {
    "mid": "/m/02cv5l",
    "description": "dumpling",
    "score": 0.79204017
    },
    {
    "mid": "/m/02wbm",
    "description": "food",
    "score": 0.76625097
    }
    ]
    }
    ]
    }

参考サイト:Google Cloud Vision API を使う準備をする

Pythonから呼び出してみる

チュートリアルがしっかりしているので,公式サイトを参考にしてもいいし,
普通にリクエストを発行する感じでも良い。
下記は,Requestsを使ってPOSTした場合の例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import requests
import json
import base64
import os

GOOGLE_CLOUD_VISION_API_URL = 'https://vision.googleapis.com/v1/images:annotate?key='
API_KEY = 'APIキーをここに書いておく'

def google_cloud_vison (image_content):
""" google_cloud_vison_APIにリクエストを投げる
"""

api_url = GOOGLE_CLOUD_VISION_API_URL + API_KEY
headers = {"content-type": "application/json"}
req_body = json.dumps({
"requests":[
{
"image":{
"content": image_content.decode('utf8')
},
"features":[{
"type":"LABEL_DETECTION",
"maxResults":5
}]
}]
})
res = requests.post(api_url, data=req_body, headers=headers)
return res.json()

def img_to_base64(filepath):
""" Base64エンコードする
"""

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)


if __name__ == "__main__":
dir = os.path.dirname(os.path.abspath(__file__))
filename = os.path.join(dir, 'target.jpg')
# print(filename)
img = img_to_base64(filename)
# print(img)
res_json = google_cloud_vison(img)
# print(res_json)
json_desc = get_descs_from_return(res_json)
print(json_desc)

おわりに

これでとりあえずRaspberry Piでカメラを動かして,写真を撮って,物体を認識することまでできた。