空飛ぶロボットのつくりかた

ロボットをつくるために必要な技術をまとめます。ロボットの未来についても考えたりします。

snowboyで遊んでみる

やりたいこと

Hey , SiriやOK, GoogleのようなHotWordを変更して、音声認識を行いたい

snowboy

install & demo

ubuntu16.04でも動いた♪

  1. install -> https://s3-us-west-2.amazonaws.com/snowboy/snowboy-releases/ubuntu1404-x86_64-1.1.1.tar.bz2

  2. sudo apt-get install python-pyaudio python3-pyaudio sox

  3. pip install pyaudio

  4. Snowboy Hotword DetectionのCreate Hotwordでtest.pmdlを作成

  5. python demo.py test.pmdl

demo.py

import snowboydecoder
import sys
import signal

interrupted = False

def signal_handler(signal, frame):
    global interrupted
    interrupted = True

def interrupt_callback():
    global interrupted
    return interrupted

if len(sys.argv) == 1:
    print("Error: need to specify model name")
    print("Usage: python demo.py your.model")
    sys.exit(-1)

model = sys.argv[1]

signal.signal(signal.SIGINT, signal_handler)

detector = snowboydecoder.HotwordDetector(model, sensitivity=0.5)
print('Listening... Press Ctrl+C to exit')

detector.start(detected_callback=snowboydecoder.ding_callback,
               interrupt_check=interrupt_callback,
               sleep_time=0.03)

detector.terminate()

このdetected_callback=snowboydecoder.ding_callbackに自作関数を入れる。

そうすると、HotWordが入った時に関数が呼ばれる。

注意

Do not append () to your callback function: the correct way is to assign detected_callback=your_func instead of detected_callback=your_func(). However, what if you have parameters to assign in your callback functions? Use a lambda function! So your callback would look like: callback=lambda: callback_function(parameters).

参考

Snowboy Hotword DetectionをRaspberry Piで動かす - Qiita

tf-pose-estimationのコード理解

やりたいこと

tf-pose-estimationを用いた面白いタスクを作るため、tf-pose-estimationを理解する

GitHub - ildoonet/tf-pose-estimation: Openpose from CMU implemented using Tensorflow with Custom Architecture for fast inference.

いつのまにかROS対応してる。素晴らしい。

rosでの動かし方

  1. sudo apt-get update

  2. sudo apt-get upgrade

  3. sudo apt-get install ros-kinetic-video-stream-opencv

  4. sudo apt-get install ros-kinetic-image-view

  5. git clone https://github.com/ildoonet/ros-video-recorder.git

  6. git clone https://github.com/ildoonet/tf-pose-estimation.git

  7. pip install -U setuptools

  8. pip install -r tf-pose-estimation/requirements.txt

  9. catkin_make

  10. roslaunch tfpose_ros demo_video.launch

Tips

launchのモデルをmobilenetに変更するとCPU only でもかろうじて動く!

msg

BodyPartElm.msg

int32 part_id
float32 x
float32 y
float32 confidence

Person,msg

BodyPartElm[] body_part

Persons.msg

Person[] persons
uint32 image_w
uint32 image_h
Header header

broadcaster_ros.py

TfPoseEstimatorROSのノード

Personsのmsg型に変換

def humans_to_msg(humans):
    persons = Persons()

    for human in humans:
        person = Person()

        for k in human.body_parts:
            body_part = human.body_parts[k]

            body_part_msg = BodyPartElm()
            body_part_msg.part_id = body_part.part_idx
            body_part_msg.x = body_part.x
            body_part_msg.y = body_part.y
            body_part_msg.confidence = body_part.score
            person.body_part.append(body_part_msg)
        persons.persons.append(person)

    return persons

以下のようにしてpathを取得することができる

        w, h = model_wh(model)
        graph_path = get_graph_path(model)

        rospack = rospkg.RosPack()
        graph_path = os.path.join(rospack.get_path('tfpose_ros'), graph_path)

estimator.py

from estimator import TfPoseEstimator

画像から予測するスクリプト

class BodyPart:
    """                                                                                                                                        
    part_idx : part index(eg. 0 for nose)                                                                                                      
    x, y: coordinate of body part                                                                                                              
    score : confidence score                                                                                                                   
    """
    __slots__ = ('uidx', 'part_idx', 'x', 'y', 'score')

    def __init__(self, uidx, part_idx, x, y, score):
        self.uidx = uidx
        self.part_idx = part_idx
        self.x, self.y = x, y
        self.score = score

    def get_part_name(self):
        return CocoPart(self.part_idx)

    def __str__(self):
        return 'BodyPart:%d-(%.2f, %.2f) score=%.2f' % (self.part_idx, self.x, self.y, self.score)

で構成されたhuman情報を返す

新しいpythonの知識

slots``__slots__``を使ってメモリを節約 - Qiita

Pythonで__slots__を使う - StoryEdit 開発日誌

@staticmethod: Pythonの「@staticmethod」はどのように役立つのか - モジログ

def str_(self): str()メソッドは、print(x)するときにも呼び出される。

networks.py

from networks import get_graph_path, model_wh

def get_graph_path(model_name):
    return {
        'cmu_640x480': './models/graph/cmu_640x480/graph_opt.pb',
        'cmuq_640x480': './models/graph/cmu_640x480/graph_q.pb',

        'cmu_640x360': './models/graph/cmu_640x360/graph_opt.pb',
        'cmuq_640x360': './models/graph/cmu_640x360/graph_q.pb',

        'mobilenet_thin_432x368': './models/graph/mobilenet_thin_432x368/graph_opt.pb',
    }[model_name]


def model_wh(model_name):
    width, height = model_name.split('_')[-1].split('x')
    return int(width), int(height)

run_webcam.py

tf-pose-estimation/run_webcam.py at master · ildoonet/tf-pose-estimation · GitHub

引数

  • parser.add_argument('--camera', type=int, default=0) : カメラ番号の選択

  • parser.add_argument('--zoom', type=float, default=1.0) : zoom

  • parser.add_argument('--model', type=str, default='mobilenet_thin_432x368', help='cmu_640x480 / cmu_640x360 / mobilenet_thin_432x368') : モデルを選択できる。mobilenetが高速。

zoom

        if args.zoom < 1.0:
            canvas = np.zeros_like(image)
            img_scaled = cv2.resize(image, None, fx=args.zoom, fy=args.zoom, interpolation=cv2.INTER_LINEAR)
            dx = (canvas.shape[1] - img_scaled.shape[1]) // 2
            dy = (canvas.shape[0] - img_scaled.shape[0]) // 2
            canvas[dy:dy + img_scaled.shape[0], dx:dx + img_scaled.shape[1]] = img_scaled
            image = canvas
        elif args.zoom > 1.0:
            img_scaled = cv2.resize(image, None, fx=args.zoom, fy=args.zoom, interpolation=cv2.INTER_LINEAR)
            dx = (img_scaled.shape[1] - image.shape[1]) // 2
            dy = (img_scaled.shape[0] - image.shape[0]) // 2
image = img_scaled[dy:image.shape[0], dx:image.shape[1]]

Google AIY Voice Kitで遊んでみる

やりたいこと

音声でサーボモータやいろいろなデバイスを操作する

f:id:robonchu:20180113115837j:plain

設定

デモ

【Google AIY Voice Kit】Google Assistant APIの設定からデモプログラムの実行まで

Lチカ

Google AIY Voice Kitで電子工作~LEDライトを点灯~

日本語化

AIY Projects kitを試してみよう | スイッチサイエンス マガジン

現状、aiyライブラリの発話関数は日本語対応してなさそう

AIYスピーカーを、ほぼ日本語版Google Homeに【Google Assistant SDKアップデート】

Voice Kitなしで実行

AIY ProjectのVoice KitをVocie Kitなしでやってみた - 知的好奇心 for IoT

GCPサンプル

サンプル アプリケーション  |  Google Cloud Speech API ドキュメント  |  Google Cloud Platform

Cloud Speech API で音声をテキストに変換する

HotWord

Snowboy Hotword Detection

snowboy/examples/Python at master · Kitt-AI/snowboy · GitHub

Snowboy Hotword DetectionをRaspberry Piで動かす - Qiita

python - How to set up wake word for Google Assistant SDK on a Raspberry Pi - Stack Overflow

virtualenvの使い方・仕組み

やりたいこと

pythonのいろんなライブラリを他の環境を汚さず試したい

使い方

インストールと起動

  1. pip install virtualenv

  2. virtualenv my_env

  3. source myenv/bin/activate

環境の保存

  1. pip freeze

無効化と削除

  1. deactivate

  2. rm -rf myenv/

ros x vertualenv

  1. pip install catkin_tools

  2. pip install empy

  3. pip install rospkg

How to install and launch Python node inside a virtualenv? - ROS Answers: Open Source Q&A Forum

python 3.x - After install ROS Kinetic, cannot import OpenCV - Stack Overflow

参考記事

virtualenv 基本的なコマンド使い方メモ - Qiita

Virtualenvの使い方 - Qiita

Pythonの仮想環境を構築できるvirtualenvを使ってみる - Qiita

virtualenvの使い方 - Qiita

Pythonの仮想環境構築(2017年版) pyenvとpyenv-virtualenvとvirtualenvとvirtualenvwrapperとpyvenvとvenv - Qiita

Python で仮想環境管理 venv の使い方 - Qiita

virtualenvを使っていろいろなライブラリを手軽にためそう | Developers.IO

virtualenvのインストール、使い方 - CHANyoshiのブログ

仕組み

ToDo

参考記事

pyenv, virtualenvの仕組み - Qiita

pyenvとvirtualenvについて勉強した時のメモ | kazsoga blog

【手順紹介】Pythonでvirtualenvをインストールしてみる - フラミナル

TX2を動かしてみる(JetPack3.1トライ)

やりたいこと

TX2でDeepLearningの何かしらのフレームワークとROSを動かす

結果

以下の記事を参考にtensorflowのインストールとOpenPoseの動作確認。

mobilenetのモデルでTX2でも8fpsくらいでる。

NVIDIA Jetson TX2でTensorFlowによる人体姿勢推定プログラムを動かせるようになるまで - Qiita

f:id:robonchu:20180107113020j:plain

以下を参考にROSのインストール。超簡単。

Install Robot Operating System (ROS) on NVIDIA Jetson TX2 - YouTube

Wiki

Jetson TX2 - eLinux.org

JetPack

Version 3.1を用いる

  • HPからダウンロード:

Jetson Download Center | NVIDIA Developer

手順

以下を参照

  1. NVIDIA JetPack Documentation

  2. JetPack 3.0 - NVIDIA Jetson TX2 - YouTube

  3. Force USB Recovery Modeの仕方はQuick Start Guide参照

参考:

Double Your Deep Learning Performance with JetPack 2.3 - YouTube

TX2のモード選択

用途に応じて消費電力と性能を選択するモードが用意されている

NVPModel - NVIDIA Jetson TX2 Development Kit - JetsonHacks

CSI camera

開発キットにはCSIカメラが取り付けられており、USBカメラに比べて処理がはやい

CSI Cameras on the TX2 (The Easy Way) - Peter Moran's Blog

https://devtalk.nvidia.com/default/topic/1005345/examples-on-how-to-use-the-jetson-carrier-board-camera-module-/

JetsonTX2 OnBoardCam · eiichiromomma/CVMLAB Wiki · GitHub

ROSでCSIカメラをlaunch

GitHub - peter-moran/jetson_csi_cam: A ROS package making it simple to use CSI cameras on the Nvidia Jetson TK1, TX1, or TX2 with ROS.

キャリアボード

価格

性能比較

f:id:robonchu:20180107151419p:plain

Deep Learning フレームワーク&OpenCV&ROSインストール

Caffe install

Caffe Deep Learning Framework - NVIDIA Jetson TX2 - YouTube

Tensorflow install

TensorFlow Install on NVIDIA Jetson TX2 - YouTube

JetsonTX2 Tensorflow · eiichiromomma/CVMLAB Wiki · GitHub

How to install TensorFlow on the NVIDIA Jetson TX2? · NVIDIA Jetson TX2 Recipes

GitHub - jetsonhacks/installTensorFlowTX2: Install TensorFlow on the NVIDIA Jetson TX2 Development Kit

Keras

Jetson TX2にKerasをインストールする - Qiita

Pytorch install

GitHub - andrewadare/jetson-tx2-pytorch: Installing PyTorch on the Nvidia Jetson TX1/TX2

Install procedure for pyTorch on NVIDIA Jetson TX1/TX2 · GitHub

OpenCV install

TensorFlow Install on NVIDIA Jetson TX2 - YouTube

ROS install

Install Robot Operating System (ROS) on NVIDIA Jetson TX2 - YouTube

OpenPoseインストール

OpenCV3を使うときはMakefieのOPENCV_VERSIONの設定を3にしてアンコメント

Tensorflow

NVIDIA Jetson TX2でTensorFlowによる人体姿勢推定プログラムを動かせるようになるまで - Qiita

GitHub - ildoonet/tf-pose-estimation: Openpose from CMU implemented using Tensorflow with Custom Architecture for fast inference.

Caffe

JetsonTX2 OpenPose · eiichiromomma/CVMLAB Wiki · GitHub

Issue

can't find hdf5.h when build caffe · Issue #156 · NVIDIA/DIGITS · GitHub

caffe fails with error undefined reference to `cv::imread(cv::String const&, int)' and undefined reference to `cv::imdecode(cv::_InputArray const&, int) · Issue #3700 · BVLC/caffe · GitHub

TX2用のinstall scriptsを使わない場合はMakefileを以下の用に書き換える必要がある↓

diff --git a/3rdparty/caffe/Makefile b/3rdparty/caffe/Makefile
index 8674f3a..46028f7 100644
--- a/3rdparty/caffe/Makefile
+++ b/3rdparty/caffe/Makefile
@@ -181,7 +181,7 @@ ifneq ($(CPU_ONLY), 1)
    LIBRARIES := cudart cublas curand
 endif
 
-LIBRARIES += glog gflags protobuf boost_system boost_filesystem m hdf5_hl hdf5
+LIBRARIES += glog gflags protobuf boost_system boost_filesystem m hdf5_serial_hl hdf5_serial
 
 # handle IO dependencies
 USE_LEVELDB ?= 1
diff --git a/3rdparty/caffe/Makefile.config.Ubuntu16_cuda8.example b/3rdparty/caffe/Makefile.config.Ubuntu16_cuda8.example
index fb92360..1f62114 100644
--- a/3rdparty/caffe/Makefile.config.Ubuntu16_cuda8.example
+++ b/3rdparty/caffe/Makefile.config.Ubuntu16_cuda8.example
@@ -100,7 +100,7 @@ PYTHON_LIB := /usr/lib /usr/local/lib
 
 # Whatever else you find you need goes here.
 INCLUDE_DIRS := $(PYTHON_INCLUDE) /usr/local/include /usr/include/hdf5/serial
-LIBRARY_DIRS := $(PYTHON_LIB) /usr/local/lib /usr/lib /usr/lib/x86_64-linux-gnu /usr/lib/x86_64-linux-gnu/hdf5/serial
+LIBRARY_DIRS := $(PYTHON_LIB) /usr/local/lib /usr/lib /usr/lib/aarch64-linux-gnu /usr/lib/aarch64-linux-gnu/hdf5/serial
 
 # If Homebrew is installed at a non standard location (for example your home directory) and you use it for general dependencies
 # INCLUDE_DIRS += $(shell brew --prefix)/include
diff --git a/Makefile b/Makefile
index 8e2109b..32a093e 100644
--- a/Makefile
+++ b/Makefile
@@ -146,7 +146,7 @@ ifneq ($(CPU_ONLY), 1)
 endif
 
 # LIBRARIES += glog gflags boost_system boost_filesystem m hdf5_hl hdf5 caffe
-LIBRARIES += glog gflags boost_system boost_filesystem m hdf5_hl hdf5
+LIBRARIES += glog gflags boost_system boost_filesystem m hdf5_serial_hl hdf5_serial
 
 # handle IO dependencies
 USE_LEVELDB ?= 1
diff --git a/ubuntu/Makefile.config.Ubuntu16_cuda8.example b/ubuntu/Makefile.config.Ubuntu16_cuda8.example
index c2940dc..053da67 100644
--- a/ubuntu/Makefile.config.Ubuntu16_cuda8.example
+++ b/ubuntu/Makefile.config.Ubuntu16_cuda8.example
@@ -78,7 +78,7 @@ CAFFE_DIR := 3rdparty/caffe/distribute
 
 # Whatever else you find you need goes here.
 INCLUDE_DIRS := /usr/local/include /usr/include/hdf5/serial
-LIBRARY_DIRS := /usr/local/lib /usr/lib /usr/lib/x86_64-linux-gnu /usr/lib/x86_64-linux-gnu/hdf5/serial
+LIBRARY_DIRS := /usr/local/lib /usr/lib /usr/lib/aarch64-linux-gnu /usr/lib/aarch64-linux-gnu/hdf5/serial
 
 # If Homebrew is installed at a non standard location (for example your home directory) and you use it for general dependencies
 # INCLUDE_DIRS += $(shell brew --prefix)/include

YOLOインストール

JetsonTX2 Yolo · eiichiromomma/CVMLAB Wiki · GitHub

CUDA8.0のインストール

https://devtalk.nvidia.com/default/topic/1001520/setting-up-cuda-manually-on-tx2/

参考

JetsonTX2 · eiichiromomma/CVMLAB Wiki · GitHub

https://devtalk.nvidia.com/default/topic/1027463/jetson-tx2/jetpack-3-2-installation-on-tx2-stops/

JetsonTX2初期セットアップ(Jetpack)からサンプルのコンパイルまでの手順 - Qiita

bash: cannot create temp file for here-document: No space left on device · GitHub

TX2を動かしてみる(JetPack3.2トライ)

やりたいこと

TX2でDeepLearningの何かしらのフレームワークとROSを動かす

結果

ToDo

Wiki

Jetson TX2 - eLinux.org

JetPack

最新のVersion 3.2を用いる

手順

以下を参照

  1. NVIDIA JetPack Documentation

  2. JetPack 3.0 - NVIDIA Jetson TX2 - YouTube

  3. Force USB Recovery Modeの仕方はQuick Start Guide参照

参考:

Double Your Deep Learning Performance with JetPack 2.3 - YouTube

Docker install

Home · open-horizon/cogwerx-jetson-tx2 Wiki · GitHub

cogwerx-jetson-tx2/tx2-post-setup at master · open-horizon/cogwerx-jetson-tx2 · GitHub

Deep Learning install

GitHub - open-horizon/cogwerx-jetson-tx2: Deep learning builds for NVIDIA Jetson TX2

Caffe install

Caffe Deep Learning Framework - NVIDIA Jetson TX2 - YouTube

Tensorflow install

TensorFlow Install on NVIDIA Jetson TX2 - YouTube

JetsonTX2 Tensorflow · eiichiromomma/CVMLAB Wiki · GitHub

How to install TensorFlow on the NVIDIA Jetson TX2? · NVIDIA Jetson TX2 Recipes

GitHub - jetsonhacks/installTensorFlowTX2: Install TensorFlow on the NVIDIA Jetson TX2 Development Kit

Keras

Jetson TX2にKerasをインストールする - Qiita

OpenCV install

TensorFlow Install on NVIDIA Jetson TX2 - YouTube

ROS install

Install Robot Operating System (ROS) on NVIDIA Jetson TX2 - YouTube

Pytorch install

GitHub - andrewadare/jetson-tx2-pytorch: Installing PyTorch on the Nvidia Jetson TX1/TX2

Install procedure for pyTorch on NVIDIA Jetson TX1/TX2 · GitHub

OpenPose

Tensorflow

NVIDIA Jetson TX2でTensorFlowによる人体姿勢推定プログラムを動かせるようになるまで - Qiita

GitHub - ildoonet/tf-pose-estimation: Openpose from CMU implemented using Tensorflow with Custom Architecture for fast inference.

Caffe

JetsonTX2 OpenPose · eiichiromomma/CVMLAB Wiki · GitHub

YOLO

JetsonTX2 Yolo · eiichiromomma/CVMLAB Wiki · GitHub

CSI camera

CSI Cameras on the TX2 (The Easy Way) - Peter Moran's Blog

https://devtalk.nvidia.com/default/topic/1005345/examples-on-how-to-use-the-jetson-carrier-board-camera-module-/

JetsonTX2 OnBoardCam · eiichiromomma/CVMLAB Wiki · GitHub

CUDA8.0のインストール

https://devtalk.nvidia.com/default/topic/1001520/setting-up-cuda-manually-on-tx2/

参考

JetsonTX2 · eiichiromomma/CVMLAB Wiki · GitHub

https://devtalk.nvidia.com/default/topic/1027463/jetson-tx2/jetpack-3-2-installation-on-tx2-stops/

JetsonTX2初期セットアップ(Jetpack)からサンプルのコンパイルまでの手順 - Qiita

ROS x Docker x ネットワーク のお勉強

 やりたいこと

dockerコンテナとホストPCでros messageの通信を行いたい

ROS

ROBOT PCでroscoreを起動

HOST PC

  1. export ROS_IP = (HOST PCのIP)

  2. export ROS_MASTER_URI=http://(ROBOTのIP):11311

    • 正確にはroscoreが立ち上がっているPCのIP

ROBOT PC

  1. export ROS_IP = (ROBOT PCのIP)

  2. exprot ROS_MASTER_URI=http://(ROBOTのIP):11311

確認方法

ROBOT_PC

  • $ rostopic pub -r 10 /topic_name std_msgs/String hello

HOST_PC

  • $ rostopic echo /topic_name

参考:

ja/ROS/Tutorials/MultipleMachines - ROS Wiki

ROS 使い方メモ -- ROS ネットワーキング

ログ表示

複数 PC に分散したノードの ROS を使った通信 - Daily Tech Blog

複数のPCで処理する方法 | ロボット理工学科 演習

ネットワーク設定 - PukiWiki

ROS 複数のPCを使ってノードを走らせる場合。: マイコン漬け

ROS x Docker

上記と基本的には同じ。

下記のように

docker inspect -f "{{.NetworkSettings.IPAddress}}" CONTAINER

でIPを調べてROS_IPにセットする。

docker-compose で立ち上げたコンテナの IP アドレスを調べる - Qiita

コンテナのIP固定の方法

docker固定IP - Qiita

Public accessible IP in container (like bridge network in VirtualBox) - DockerEngine - Docker Forums

参考:

Docker + ROS(kinetic)でチュートリアル - Qiita

dockerでROSを試したい - Qiita

Exposing ROS Containers to Host Machine - ROS Answers: Open Source Q&A Forum

Small ROS Network Example · GitHub

Challenges with running ROS on Kubernetes | Service Engineering (ICCLab & SPLab)

Docker v1.9のマルチホストネットワーク機能を使ったROS通信が可能か検証してみた - Qiita

Docker単体

参考:

Docker の基本学習 ~ コンテナ間のリンク - Qiita

マルチホストでのDocker Container間通信 第1回: Dockerネットワークの基礎 - UZABASE Tech Blog

Dockerのマルチホストネットワークで複数ホスト間を繋ぐ仮想ネットワークを作る(Dockerの最新機能を使ってみよう:第1回) | さくらのナレッジ

[社内向け]Docker勉強会(コンテナ同士の通信) - Qiita

4.5 Dockerネットワークについて