|
| 1 | +# Developed from code sourced from: |
| 2 | +# Copyright Amazon AWS DeepLens, 2017 |
| 3 | +# Copyright Amazon AWS DeepLens, 2018 |
| 4 | +# And Mike Chambers @ Linux Academy |
| 5 | + |
| 6 | +import os |
| 7 | +import greengrasssdk |
| 8 | +from threading import Timer, Thread, Event |
| 9 | +import time |
| 10 | +import awscam |
| 11 | +import cv2 |
| 12 | +import mo |
| 13 | +import json |
| 14 | +import numpy as np |
| 15 | + |
| 16 | + |
| 17 | +class LocalDisplay(Thread): |
| 18 | + |
| 19 | + def __init__(self, resolution): |
| 20 | + # Initialize the base class, so that the object can run on its own |
| 21 | + # thread. |
| 22 | + super(LocalDisplay, self).__init__() |
| 23 | + # List of valid resolutions |
| 24 | + RESOLUTION = {'1080p' : (1920, 1080), '720p' : (1280, 720), '480p' : (858, 480)} |
| 25 | + if resolution not in RESOLUTION: |
| 26 | + raise Exception("Invalid resolution") |
| 27 | + self.resolution = RESOLUTION[resolution] |
| 28 | + # Initialize the default image to be a white canvas. Clients |
| 29 | + # will update the image when ready. |
| 30 | + self.frame = cv2.imencode('.jpg', 255*np.ones([640, 480, 3]))[1] |
| 31 | + self.stop_request = Event() |
| 32 | + |
| 33 | + def run(self): |
| 34 | + # Path to the FIFO file. The lambda only has permissions to the tmp |
| 35 | + # directory. Pointing to a FIFO file in another directory |
| 36 | + # will cause the lambda to crash. |
| 37 | + result_path = '/tmp/results.mjpeg' |
| 38 | + # Create the FIFO file if it doesn't exist. |
| 39 | + if not os.path.exists(result_path): |
| 40 | + os.mkfifo(result_path) |
| 41 | + # This call will block until a consumer is available |
| 42 | + with open(result_path, 'w') as fifo_file: |
| 43 | + while not self.stop_request.isSet(): |
| 44 | + try: |
| 45 | + # Write the data to the FIFO file. This call will block |
| 46 | + # meaning the code will come to a halt here until a consumer |
| 47 | + # is available. |
| 48 | + fifo_file.write(self.frame.tobytes()) |
| 49 | + except IOError: |
| 50 | + continue |
| 51 | + |
| 52 | + def set_frame_data(self, frame): |
| 53 | + ret, jpeg = cv2.imencode('.jpg', cv2.resize(frame, self.resolution)) |
| 54 | + if not ret: |
| 55 | + raise Exception('Failed to set frame data') |
| 56 | + self.frame = jpeg |
| 57 | + |
| 58 | + def join(self): |
| 59 | + self.stop_request.set() |
| 60 | + |
| 61 | +def greengrass_infinite_infer_run(): |
| 62 | + try: |
| 63 | + input_width = 224 |
| 64 | + input_height = 224 |
| 65 | + |
| 66 | + model_name = "image-classification" |
| 67 | + model_type = "classification" |
| 68 | + |
| 69 | + client = greengrasssdk.client('iot-data') |
| 70 | + |
| 71 | + iotTopic = '$aws/things/{}/infer'.format(os.environ['AWS_IOT_THING_NAME']) |
| 72 | + |
| 73 | + local_display = LocalDisplay('480p') |
| 74 | + local_display.start() |
| 75 | + |
| 76 | + error, model_path = mo.optimize(model_name,input_width,input_height, aux_inputs={'--epoch': 30}) |
| 77 | + mcfg = {"GPU": 1} |
| 78 | + |
| 79 | + print("model_path: " + model_path) |
| 80 | + |
| 81 | + model = awscam.Model(model_path, mcfg) |
| 82 | + |
| 83 | + client.publish(topic=iotTopic, payload="Model loaded") |
| 84 | + |
| 85 | + with open('pinehead_labels.txt', 'r') as f: |
| 86 | + labels = [l.rstrip() for l in f] |
| 87 | + |
| 88 | + num_top_k = 2 |
| 89 | + |
| 90 | + # Send a starting message to IoT console |
| 91 | + client.publish(topic=iotTopic, payload="Inference is starting") |
| 92 | + |
| 93 | + doInfer = True |
| 94 | + while doInfer: |
| 95 | + # Get a frame from the video stream |
| 96 | + ret, frame = awscam.getLastFrame() |
| 97 | + # Raise an exception if failing to get a frame |
| 98 | + if ret == False: |
| 99 | + raise Exception("Failed to get frame from the stream") |
| 100 | + |
| 101 | + # Resize frame to fit model input requirement |
| 102 | + s = frame.shape |
| 103 | + cropped = frame[0:s[0], int((s[1]-s[0])/2):s[0]+int((s[1]-s[0])/2)] |
| 104 | + frameResize = cv2.resize(cropped, (input_width, input_height)) |
| 105 | + |
| 106 | + # Run model inference on the resized frame |
| 107 | + inferOutput = model.doInference(frameResize) |
| 108 | + |
| 109 | + parsed_inference_results = model.parseResult(model_type, model.doInference(frameResize)) |
| 110 | + |
| 111 | + top_k = parsed_inference_results[model_type][0:num_top_k-1] |
| 112 | + |
| 113 | + msg = "{" |
| 114 | + msg += '"{}"'.format(labels[top_k[0]["label"]]) |
| 115 | + msg += "}" |
| 116 | + |
| 117 | + client.publish(topic=iotTopic, payload = msg) |
| 118 | + |
| 119 | + font = cv2.FONT_HERSHEY_SIMPLEX |
| 120 | + |
| 121 | + cv2.putText(frame, labels[top_k[0]["label"]], (10, 140), font, 5, (174, 235, 52), 10) |
| 122 | + local_display.set_frame_data(frame) |
| 123 | + |
| 124 | + |
| 125 | + except Exception as e: |
| 126 | + msg = "myModel Lambda failed: " + str(e) |
| 127 | + client.publish(topic=iotTopic, payload=msg) |
| 128 | + |
| 129 | + # Asynchronously schedule this function to be run again in 15 seconds |
| 130 | + Timer(15, greengrass_infinite_infer_run).start() |
| 131 | + |
| 132 | +# Execute the function above |
| 133 | +greengrass_infinite_infer_run() |
| 134 | + |
| 135 | +# This is a dummy handler and will not be invoked |
| 136 | +# Instead the code above will be executed in an infinite loop for our example |
| 137 | +def function_handler(event, context): |
| 138 | + return |
0 commit comments