├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── cloudbuild.yaml ├── conf ├── jupyter_notebook_config.py ├── requirements.txt └── supervisord.conf └── examples └── webcam_obj_detector_opencv.py /.gitignore: -------------------------------------------------------------------------------- 1 | /old/ 2 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM balenalib/raspberrypi3-debian:buster 2 | RUN [ "cross-build-start" ] 3 | 4 | ARG MAYOR_REVISION 5 | ARG MINOR_REVISION 6 | ARG BUILD_ID 7 | 8 | #labeling 9 | LABEL org.label-schema.name="raspbian-edgetpu" \ 10 | org.label-schema.description="Docker running Raspbian including Coral Edge-TPU libraries" \ 11 | org.label-schema.url="https://lemariva.com" \ 12 | org.label-schema.vcs-url="https://github.com/lemariva/raspbian-EdgeTPU" \ 13 | org.label-schema.vendor="LeMaRiva|Tech info@lemariva.com" \ 14 | org.label-schema.version="${MAYOR_REVISION}.${MINOR_REVISION}.${BUILD_ID}" 15 | 16 | ENV READTHEDOCS True 17 | ENV NODE_OPTIONS "--max-old-space-size=2048" 18 | ENV CONFIG_PATH "/root/.jupyter/jupyter_notebook_config.py" 19 | 20 | #do installation 21 | RUN apt-get update \ 22 | && apt-get install -y --no-install-recommends openssh-server \ 23 | #do users 24 | && echo 'root:root' | chpasswd \ 25 | && sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config \ 26 | && sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd \ 27 | && mkdir /var/run/sshd 28 | 29 | #copy files 30 | RUN mkdir /notebooks 31 | COPY ./examples/ /notebooks/ 32 | COPY ./conf/jupyter_notebook_config.py ${CONFIG_PATH} 33 | COPY ./conf/requirements.txt /tmp/requirements.txt 34 | 35 | #nodejs for notebooks 36 | RUN curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - \ 37 | && apt-get install -y nodejs 38 | 39 | #install libraries for camera and opencv2 40 | RUN apt-get install -y --no-install-recommends build-essential git wget feh pkg-config libjpeg-dev zlib1g-dev libssl-dev libffi-dev \ 41 | libraspberrypi0 libraspberrypi-dev libraspberrypi-doc libraspberrypi-bin libfreetype6-dev libxml2 libopenjp2-7 \ 42 | libatlas-base-dev libjasper-dev libqtgui4 libqt4-test libavformat-dev libswscale-dev \ 43 | python3-dev python3-pip python3-setuptools python3-wheel python3-pil python3-zmq python3-opencv \ 44 | python3-matplotlib python3-numpy python3-scipy 45 | 46 | #python libraries 47 | RUN python3 -m pip install --upgrade pip 48 | RUN python3 -m pip install --ignore-installed -r /tmp/requirements.txt 49 | 50 | #jupyter packages 51 | #RUN NODE_OPTIONS=--max_old_space_size=2048 jupyter nbextension enable --py widgetsnbextension \ 52 | # && NODE_OPTIONS=--max_old_space_size=2048 jupyter labextension install --minimize=False @jupyter-widgets/jupyterlab-manager \ 53 | # && NODE_OPTIONS=--max_old_space_size=2048 jupyter labextension install --minimize=False jupyter-webrtc 54 | 55 | #install live camera libraries 56 | RUN apt-get install libgstreamer1.0-0 gstreamer1.0-tools \ 57 | gstreamer1.0-plugins-base gstreamer1.0-plugins-good \ 58 | gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly v4l-utils 59 | 60 | #downloading library file 61 | RUN echo "deb https://packages.cloud.google.com/apt coral-edgetpu-stable main" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list \ 62 | && echo "deb https://packages.cloud.google.com/apt coral-cloud-stable main" | sudo tee /etc/apt/sources.list.d/coral-cloud.list \ 63 | && curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add - \ 64 | && apt-get update \ 65 | && apt-get install -y python3-pycoral python3-tflite-runtime 66 | 67 | #SSL for jupyter 68 | RUN mkdir /root/certs/ \ 69 | && cd /root/certs/ \ 70 | && openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout mykey.key -out mycert.pem -subj '/O=LeMaRiva|Tech/C=DE' 71 | 72 | #loading pretrained models 73 | WORKDIR /notebooks 74 | 75 | RUN apt-get autoremove \ 76 | && rm -rf /tmp/* \ 77 | && rm -rf /var/lib/apt/lists/* 78 | 79 | #copy supervisord files 80 | COPY "./conf/supervisord.conf" /etc/supervisor/conf.d/supervisord.conf 81 | RUN mkdir /var/log/supervisord/ 82 | 83 | #supervisord 84 | CMD ["/usr/local/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf"] 85 | 86 | #opencv2 bug on arm (Undefined reference to __atomic) 87 | ENV LD_PRELOAD "/usr/lib/arm-linux-gnueabihf/libatomic.so.1.2.0" 88 | 89 | #SSH Port 90 | EXPOSE 22 8888 8080 91 | 92 | #set stop signal 93 | STOPSIGNAL SIGTERM 94 | 95 | #stop processing ARM emulation (comment out next line if built on Raspberry) 96 | RUN [ "cross-build-end" ] 97 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # raspbian-EdgeTPU 2 | This Docker image includes the libraries and packages to work with the Coral USB Accelerator (Google). The based image is `balenalib/raspberrypi3-debian:buster`. 3 | 4 | The image contains the following packages/libraries: 5 | * Python 3.7.x 6 | * NodeJS 12.x 7 | * Python Packages: 8 | * numpy, matplotlib, pil, zmq 9 | * supervisor, tornado, picamera, python-periphery 10 | * jupyter, cython, jupyterlab, ipywebrtc, opencv-python 11 | * google-auth, oauthlib, imutils 12 | * Other libraries included (check the `Dockerfile`) 13 | 14 | A Jupyterlab is available (`https://:8888`) in which you can write code to process images obtained e.g. from the Pi camera. 15 | 16 | An examples using the Coral USB Accelerator is also included: 17 | * `webcam_obj_detector_opencv.py`: detects and classifies objects on the fly processing the images taken with the Pi camera. The streaming images are available over http (`http://:8080`). It uses the `opencv` library to get images from the camera (USB port or CSI connector). 18 | 19 | More examples can be found on the [Coral website](https://coral.ai/examples/). Git is install, thus, you can download the repositories inside jupyter by typing e.g.: 20 | ``` 21 | !git clone https://github.com/google-coral/project-posenet.git 22 | ``` 23 | 24 | To run the container type the following on a Raspberry Pi terminal: 25 | ``` 26 | docker run -d --privileged -p 25:22 -p 8080:8080 -p 8888:8888 -e PASSWORD=<> --restart unless-stopped -v /dev/bus/usb:/dev/bus/usb lemariva/raspbian-edgetpu 27 | ``` 28 | You need to activate the camera interface using `sudo raspi-config` to use live images of the Raspberry Pi camera. 29 | 30 | ## More Information 31 | More information about the repository can be found on the following links: 32 | * [#Edge-TPU: Coral USB Accelerator + rPI + Docker](https://lemariva.com/blog/2019/03/edge-tpu-coral-usb-accelerator-rpi-docker) 33 | * [#Edge-TPU: Hands-On with Google's Coral USB accelerator](https://lemariva.com/blog/2019/04/edge-tpu-coral-usb-accelerator-dockerized) 34 | 35 | ## Licence 36 | * Apache 2.0 -------------------------------------------------------------------------------- /cloudbuild.yaml: -------------------------------------------------------------------------------- 1 | steps: 2 | - name: 'gcr.io/cloud-builders/docker' 3 | args: [ 'build', 4 | '-t', 'gcr.io/$PROJECT_ID/raspbian-edgetpu:${_MAYOR_REVISION}.${_MINOR_REVISION}.${_BUILD_ID}', 5 | '--build-arg', 6 | 'BUILD_ID=${_BUILD_ID}', 7 | '--build-arg', 8 | 'MAYOR_REVISION=${_MAYOR_REVISION}', 9 | '--build-arg', 10 | 'MINOR_REVISION=${_MINOR_REVISION}', 11 | '.'] 12 | substitutions: # default values 13 | _MAYOR_REVISION: "2" 14 | _MINOR_REVISION: "2" 15 | _BUILD_ID: "1" 16 | timeout: 7200s 17 | images: 18 | - 'gcr.io/$PROJECT_ID/raspbian-edgetpu' -------------------------------------------------------------------------------- /conf/jupyter_notebook_config.py: -------------------------------------------------------------------------------- 1 | import os 2 | from IPython.lib import passwd 3 | 4 | #c = c # pylint:disable=undefined-variable 5 | c = get_config() 6 | c.NotebookApp.ip = '0.0.0.0' 7 | c.NotebookApp.certfile = u'/root/certs/mycert.pem' 8 | c.NotebookApp.keyfile = u'/root/certs/mykey.key' 9 | c.NotebookApp.port = int(os.getenv('PORT', 8888)) 10 | c.NotebookApp.open_browser = False 11 | c.NotebookApp.notebook_dir = '/notebooks' 12 | 13 | # sets a password if PASSWORD is set in the environment 14 | if 'PASSWORD' in os.environ: 15 | password = os.environ['PASSWORD'] 16 | if password: 17 | c.NotebookApp.password = passwd(password) 18 | else: 19 | c.NotebookApp.password = '' 20 | c.NotebookApp.token = '' 21 | del os.environ['PASSWORD'] 22 | -------------------------------------------------------------------------------- /conf/requirements.txt: -------------------------------------------------------------------------------- 1 | pyzmq==21.0.1 2 | supervisor==4.2.1 3 | tornado==6.1 4 | picamera==1.13 5 | imutils==0.5.4 6 | python-periphery==2.2.0 7 | cython==0.29.21 8 | jupyter==1.0.0 9 | jupyterlab==3.0.5 10 | ipywebrtc==0.5.0 11 | google-auth==1.24.0 12 | oauthlib==3.1.0 13 | -------------------------------------------------------------------------------- /conf/supervisord.conf: -------------------------------------------------------------------------------- 1 | [supervisord] 2 | nodaemon=true 3 | logfile=/var/log/supervisord/supervisord.log 4 | 5 | [program:ssh] 6 | command=/usr/sbin/sshd -D 7 | 8 | [program:jupyter] 9 | command=jupyter lab --allow-root -y --no-browser --ip=0.0.0.0 --config=/root/.jupyter/jupyter_notebook_config.py 10 | autorestart=false 11 | 12 | #[program:object-detector] 13 | #command=python3 /notebooks/webcam_obj_detector_opencv.py --model /notebooks/test_data/mobilenet_ssd_v2_coco_quant_postprocess_edgetpu.tflite --labels /notebooks/test_data/coco_labels.txt 14 | #autorestart=false -------------------------------------------------------------------------------- /examples/webcam_obj_detector_opencv.py: -------------------------------------------------------------------------------- 1 | import os 2 | import io 3 | import time 4 | import base64 5 | import argparse 6 | import logging 7 | import socketserver 8 | from http import server 9 | from threading import Condition 10 | 11 | import cv2 12 | from imutils.video import WebcamVideoStream 13 | from imutils.video import FPS 14 | 15 | import numpy as np 16 | 17 | from pycoral.adapters.common import input_size 18 | from pycoral.adapters.detect import get_objects 19 | from pycoral.utils.dataset import read_label_file 20 | from pycoral.utils.edgetpu import make_interpreter 21 | from pycoral.utils.edgetpu import run_inference 22 | 23 | # Parameters 24 | AUTH_USERNAME = os.environ.get('AUTH_USERNAME', 'pi') 25 | AUTH_PASSWORD = os.environ.get('AUTH_PASSWORD', 'picamera') 26 | AUTH_BASE64 = base64.b64encode('{}:{}'.format(AUTH_USERNAME, AUTH_PASSWORD).encode('utf-8')) 27 | BASIC_AUTH = 'Basic {}'.format(AUTH_BASE64.decode('utf-8')) 28 | RESOLUTION = os.environ.get('RESOLUTION', '640x480').split('x') 29 | RESOLUTION_X = int(RESOLUTION[0]) 30 | RESOLUTION_Y = int(RESOLUTION[1]) 31 | FRAMERATE = int(os.environ.get('FRAMERATE', '30')) 32 | ROTATION = int(os.environ.get('ROTATE', 0)) 33 | HFLIP = os.environ.get('HFLIP', 'false').lower() == 'true' 34 | VFLIP = os.environ.get('VFLIP', 'false').lower() == 'true' 35 | USBCAMNO = os.environ.get('USBCAMNO', 0) # change it to get images from other cameras e.g. 1 36 | QUALITY = os.environ.get('QUALITY', 50) 37 | 38 | PAGE = """\ 39 | 40 | 41 | edgeTPU Object Detection 42 | 43 | 44 | 45 | 46 | 47 | """.format(RESOLUTION_X, RESOLUTION_Y) 48 | 49 | 50 | class StreamingOutput(object): 51 | def __init__(self): 52 | self.frame = None 53 | self.buffer = io.BytesIO() 54 | self.condition = Condition() 55 | 56 | def write(self, buf): 57 | if buf.startswith(b'\xff\xd8'): 58 | # New frame, copy the existing buffer's content and notify all 59 | # clients it's available 60 | self.buffer.truncate() 61 | with self.condition: 62 | self.frame = self.buffer.getvalue() 63 | self.condition.notify_all() 64 | self.buffer.seek(0) 65 | return self.buffer.write(buf) 66 | 67 | 68 | class StreamingHandler(server.BaseHTTPRequestHandler): 69 | def do_GET(self): 70 | if self.headers.get('Authorization') is None: 71 | self.do_AUTHHEAD() 72 | self.wfile.write(b'no auth header received') 73 | elif self.headers.get('Authorization') == BASIC_AUTH: 74 | self.authorized_get() 75 | else: 76 | self.do_AUTHHEAD() 77 | self.wfile.write(b'not authenticated') 78 | 79 | def do_AUTHHEAD(self): 80 | self.send_response(401) 81 | self.send_header('WWW-Authenticate', 'Basic realm=\"picamera\"') 82 | self.send_header('Content-type', 'text/html') 83 | self.end_headers() 84 | 85 | def append_objs_to_img(self, cv2_im, inference_size, objs, labels): 86 | height, width, channels = cv2_im.shape 87 | scale_x, scale_y = width / inference_size[0], height / inference_size[1] 88 | for obj in objs: 89 | bbox = obj.bbox.scale(scale_x, scale_y) 90 | x0, y0 = int(bbox.xmin), int(bbox.ymin) 91 | x1, y1 = int(bbox.xmax), int(bbox.ymax) 92 | 93 | percent = int(100 * obj.score) 94 | label = '{}% {}'.format(percent, labels.get(obj.id, obj.id)) 95 | 96 | cv2_im = cv2.rectangle(cv2_im, (x0, y0), (x1, y1), (0, 255, 0), 2) 97 | cv2_im = cv2.putText(cv2_im, label, (x0, y0+30), 98 | cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 0, 0), 2) 99 | return cv2_im 100 | 101 | def authorized_get(self): 102 | if self.path == '/': 103 | self.send_response(301) 104 | self.send_header('Location', '/index.html') 105 | self.end_headers() 106 | elif self.path == '/index.html': 107 | content = PAGE.encode('utf-8') 108 | self.send_response(200) 109 | self.send_header('Content-Type', 'text/html') 110 | self.send_header('Content-Length', len(content)) 111 | self.end_headers() 112 | self.wfile.write(content) 113 | elif self.path == '/stream.mjpg': 114 | self.send_response(200) 115 | self.send_header('Age', 0) 116 | self.send_header('Cache-Control', 'no-cache, private') 117 | self.send_header('Pragma', 'no-cache') 118 | self.send_header('Content-Type', 'multipart/x-mixed-replace; boundary=FRAME') 119 | self.end_headers() 120 | try: 121 | stream_video = io.BytesIO() 122 | fps.start() 123 | while True: 124 | # getting image 125 | frame = camera.read() 126 | cv2_im = frame 127 | 128 | # cv2 coding 129 | cv2_im_rgb = cv2.cvtColor(cv2_im, cv2.COLOR_BGR2RGB) 130 | cv2_im_rgb = cv2.resize(cv2_im_rgb, inference_size) 131 | if VFLIP: 132 | cv2_im_rgb = cv2.flip(cv2_im_rgb, 0) 133 | if HFLIP: 134 | cv2_im_rgb = cv2.flip(cv2_im_rgb, 1) 135 | 136 | # object detection 137 | run_inference(interpreter, cv2_im_rgb.tobytes()) 138 | objs = get_objects(interpreter, args.threshold)[:args.top_k] 139 | 140 | cv2_im = self.append_objs_to_img(cv2_im, inference_size, objs, labels) 141 | r, buf = cv2.imencode(".jpg", cv2_im) 142 | 143 | self.wfile.write(b'--FRAME\r\n') 144 | self.send_header('Content-type','image/jpeg') 145 | self.send_header('Content-length',str(len(buf))) 146 | self.end_headers() 147 | self.wfile.write(bytearray(buf)) 148 | self.wfile.write(b'\r\n') 149 | fps.update() 150 | 151 | except Exception as e: 152 | logging.warning( 153 | 'Removed streaming client %s: %s', 154 | self.client_address, str(e)) 155 | 156 | else: 157 | self.send_error(404) 158 | self.end_headers() 159 | 160 | 161 | class StreamingServer(socketserver.ThreadingMixIn, server.HTTPServer): 162 | allow_reuse_address = True 163 | daemon_threads = True 164 | 165 | 166 | if __name__ == '__main__': 167 | default_model_dir = './' 168 | default_model = 'mobilenet_ssd_v2_coco_quant_postprocess_edgetpu.tflite' 169 | default_labels = 'coco_labels.txt' 170 | 171 | parser = argparse.ArgumentParser() 172 | parser.add_argument('--model', help='.tflite model path', 173 | default=os.path.join(default_model_dir,default_model)) 174 | parser.add_argument('--labels', help='label file path', 175 | default=os.path.join(default_model_dir, default_labels)) 176 | parser.add_argument('--top_k', type=int, default=3, 177 | help='number of categories with highest score to display') 178 | parser.add_argument('--threshold', type=float, default=0.1, 179 | help='classifier score threshold') 180 | parser.add_argument('--camera_idx', type=int, help='Index of which video source to use. ', default = USBCAMNO) 181 | 182 | args = parser.parse_args() 183 | 184 | interpreter = make_interpreter(args.model) 185 | interpreter.allocate_tensors() 186 | labels = read_label_file(args.labels) 187 | inference_size = input_size(interpreter) 188 | 189 | camera = WebcamVideoStream(src=args.camera_idx).start() 190 | camera.stream.set(cv2.CAP_PROP_FPS, FRAMERATE) 191 | camera.stream.set(cv2.CAP_PROP_FRAME_WIDTH, RESOLUTION_X) 192 | camera.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, RESOLUTION_Y) 193 | 194 | fps = FPS() 195 | 196 | try: 197 | address = ('', 8080) 198 | server = StreamingServer(address, StreamingHandler) 199 | server.serve_forever() 200 | except: 201 | cv2.destroyAllWindows() 202 | camera.stop() 203 | fps.stop() 204 | print("[INFO] elasped time: {:.2f}".format(fps.elapsed())) 205 | print("[INFO] approx. FPS: {:.2f}".format(fps.fps())) --------------------------------------------------------------------------------