Created
October 12, 2016 04:41
-
-
Save sweemeng/c01dfb5b6ce16a71d4d4bd698cc8d099 to your computer and use it in GitHub Desktop.
Google vision API example used with raspberry pi, pi camera with GPIO to trigger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
accepted: | |
- mobile phone | |
- electronics | |
- paper |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from picamera import PiCamera | |
import time | |
import base64 | |
from googleapiclient import discovery | |
from oauth2client.client import GoogleCredentials | |
import RPi.GPIO as GPIO | |
import yaml | |
BUTTON_PIN = 11 | |
RED_PIN = 13 | |
GREEN_PIN = 15 | |
def generate_image(): | |
camera = PiCamera() | |
file_name = "%s.jpg" % time.time() | |
camera.capture(file_name) | |
camera.close() | |
return file_name | |
def generate_label(filename): | |
accepted_list = yaml.load(open("config.yaml")) | |
accepted = False | |
credentials = GoogleCredentials.get_application_default() | |
service = discovery.build('vision', 'v1', credentials=credentials) | |
with open(filename, 'rb') as image: | |
image_content = base64.b64encode(image.read()) | |
service_request = service.images().annotate(body={ | |
'requests': [{ | |
'image': { | |
'content': image_content.decode('UTF-8') | |
}, | |
'features': [{ | |
'type': 'LABEL_DETECTION', | |
'maxResults': 1 | |
}] | |
}] | |
}) | |
responses = service_request.execute() | |
# label = response['responses'][0]['labelAnnotations'][0]['description'] | |
for response in responses['responses']: | |
labels = response['labelAnnotations'] | |
for label in labels: | |
if label['description'] in accepted_list["accepted"]: | |
accepted = True | |
print("caught it") | |
print('Found label: %s for %s' % (label, filename)) | |
return accepted | |
if __name__ == "__main__": | |
GPIO.setmode(GPIO.BOARD) | |
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) | |
GPIO.setup(RED_PIN, GPIO.OUT) | |
GPIO.setup(GREEN_PIN, GPIO.OUT) | |
# button pressed | |
try: | |
while True: | |
if GPIO.input(BUTTON_PIN): | |
GPIO.output(GREEN_PIN, 1) | |
GPIO.output(RED_PIN, 1) | |
images = generate_image() | |
accepted=generate_label(images) | |
if accepted: | |
GPIO.output(RED_PIN, 0) | |
else: | |
GPIO.output(GREEN_PIN, 0) | |
print("boom") | |
time.sleep(5) | |
GPIO.output(15, 0) | |
GPIO.output(13, 0) | |
time.sleep(0.1) | |
print("bam") | |
except Exception as e: | |
print(e) | |
GPIO.cleanup() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment