Raspberry Pi + Apache + Google Cloud Vision API + Slack API 사용하기

목적


  • Raspberry Pi를 설정합니다.
  • 웹 서버(Apache HTTP Server)를 설치합니다.
  • 웹캠으로 촬영합니다.
  • Google Cloud Vision API에서 라벨링
  • 라벨링 결과를 Slack에 보냅니다.

  • 전체상





    동작 확인



    http://192.168.x.x/test.jpg
    (Raspberry Pi의 IP 주소)



    받은 슬랙



    아파치


    sudo chmod 777 /var/www/html
    

    파이썬



    test.py
    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    import os
    import io
    from time import sleep
    from datetime import datetime
    import subprocess
    import requests
    import json
    from google.cloud import vision
    from google.cloud.vision import types
    
    def exec_cmd(cmd):
        #r = subprocess.check_output(cmd, shell=True)
        #return r.decode('utf-8').strip()
        subprocess.call(cmd, shell=True)
    
    def take_photo():
        #now = datetime.now()
        #f = now.strftime('%Y-%m-%d_%H-%M-%S') + '.jpg'
        f = 'test.jpg'
        exec_cmd('fswebcam ' + f)
    
    def get_label(file_name):
        #key_path = '/home/pi/*/yourkey.json'
        #os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = key_path
    
        client = vision.ImageAnnotatorClient()
    
        with io.open(file_name, 'rb') as image_file:
            content = image_file.read()
    
        image = types.Image(content=content)
        response = client.label_detection(image=image)
        labels = response.label_annotations
        d = labels[0].description
        s = labels[0].score
        text = 'label: ' + d + ' score: ' + '{:.2f}'.format(s)
        return text
    
    def send_slack(text):
        WEB_HOOK_URL = 'https://hooks.slack.com/services/xxx'
        requests.post(WEB_HOOK_URL, data = json.dumps({
            'text': text,
            }))
    
    if __name__ == '__main__':
        take_photo()
        txt = get_label('test.jpg')
        send_slack(txt)
    

    쉘 스크립트



    test.sh
    sleep 3
    python3 test.py
    cp test.jpg /var/www/html/ 
    

    좋은 웹페이지 즐겨찾기