« ファミコン・スーファミソフトが80本収録されたゲーム機”Retro-bit GENERATIONS” | トップページ | Intel以外のCPUがまだ熱かった90年代終わりのx86互換CPUたち »

2017年1月18日 (水)

TensorFlowを使って”ゴキブリ”探知機を作ろうとしてみた

微妙な言い回しのタイトルですが、お察しのとおり思い通りのものにはなりませんでした。

人類誕生よりはるか前、3億年以上昔から存在するといわれている”ゴキ”。

現代社会においても平和な家庭を突如乱す存在として君臨し続け、未だ人類との死闘を続けている、まさに昆虫界四天王の一人(一匹?)

幸い我が家はまだゴキ野郎の襲撃を受けたことはありませんが(ムカデは一度ありますが)、いずれ来るであろうこの”悪魔”との闘いに備えて、ゴキ探知機を作れないかと考えてみました。

一番手っ取り早いのは「人工知能ライブラリ”TensorFlow”をRaspberry Pi 3に入れていろいろなものを画像認識させてみた」記事で使った”inception-2015-12-05”のライブラリを使って”ゴキブリ”を認識させること。

人工知能をいきなりゴキブリ発見器に使うというのもなんだかもったいない気がしますが・・・

いや人類長年の敵なればこそ最先端の科学で勝負

ところが、以前TensorFlowを入れたものの、その後Raspberry Pi 3の起動ディスクが吹っ飛んでしまったので、再びTensorFlow環境を構築しなきゃいけません。

以前の記事(人工知能ライブラリ”TensorFlow”をRaspberry Pi 3に入れていろいろなものを画像認識させてみた: EeePCの軌跡)を参考に、TensorFlowを再構築します。

まずはコマンドラインで

$ sudo apt-get install python-pip python-dev

を実行。

続いて、

pip install numpy

を実行します。

で、そのあとTensorFlowを入れるんですが以前の記事で使った0.8.0はもう存在せず。昔の記事と同じコマンドでは入手不能に。

現在入手可能なのは「0.11.0」なため、ちょっと手順が異なります。

https://github.com/samjabrahams/tensorflow-on-raspberry-piを参考に、以下のように実行します。

$ wget https://github.com/samjabrahams/tensorflow-on-raspberry-pi/releases/download/v0.11.0/tensorflow-0.11.0-cp27-none-linux_armv7l.whl

$ sudo pip install tensorflow-0.11.0-cp27-none-linux_armv7l.whl

これでTensorFlow環境は導入完了。

で、以前のようにすぐに画像認識できるコード”classify_image.py”を使ってテスト・・・

といきたかったんですが、上のコマンドを実行しただけではこのコードが入手できなくなってました。

ということで、以下のサイトから”classify_image.py”を入手します。

https://github.com/MartinThoma/algorithms/blob/master/ML/ImageNet-classification/tensorflow/classify_image.py

これでようやくTensorFlowの画像認識が使えるようになります。

まずは学習データを入手するために、一度”classify_image.py”を実行。

$ python classify_image.py

なにやらダウンロードがはじまり、パンダを認識したというメッセージが出て終了するはずです。

ここで/home/piの直下に”imagenet”というディレクトリを作り、この学習データを持ってきます。

$ mkdir imagenet

$ cp /tmp/imagenet/* imagenet

続いて”classify_image.py”をテキストエディタで開き、63行目の

'model_dir', '/tmp/imagenet',

'model_dir', '/home/pi/imagenet',

と書き換えます。

続いて192行目から

    f = open( "test.txt", "a" )
    try:
      f.write( '%s %s\n' % (image, human_string))
    finally:
      f.close()

というのを書き加えておきます。

できたコードは以下。

classify_image.py

# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

"""Simple image classification with Inception.
Run image classification with Inception trained on ImageNet 2012 Challenge data
set.
This program creates a graph from a saved GraphDef protocol buffer,
and runs inference on an input JPEG image. It outputs human readable
strings of the top 5 predictions along with their probabilities.
Change the --image_file argument to any jpg image to compute a
classification of that image.
Please see the tutorial and website for a detailed description of how
to use this script to perform image recognition.
https://tensorflow.org/tutorials/image_recognition/
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os.path
import re
import sys
import tarfile

import numpy as np
from six.moves import urllib
import tensorflow as tf

FLAGS = tf.app.flags.FLAGS

# classify_image_graph_def.pb:
#   Binary representation of the GraphDef protocol buffer.
# imagenet_synset_to_human_label_map.txt:
#   Map from synset ID to a human readable string.
# imagenet_2012_challenge_label_map_proto.pbtxt:
#   Text representation of a protocol buffer mapping a label to synset ID.
tf.app.flags.DEFINE_string(
#    'model_dir', '/tmp/imagenet',
    'model_dir', '/home/pi/imagenet',
    """Path to classify_image_graph_def.pb, """
    """imagenet_synset_to_human_label_map.txt, and """
    """imagenet_2012_challenge_label_map_proto.pbtxt.""")
tf.app.flags.DEFINE_string('image_file', '',
                      
    """Absolute path to image file.""")
tf.app.flags.DEFINE_integer('num_top_predictions', 5,
                      
     """Display this many predictions.""")

# pylint: disable=line-too-long
DATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'
# pylint: enable=line-too-long


class NodeLookup(object):
  """Converts integer node ID's to human readable labels."""

  def __init__(self,
               label_lookup_path=None,
               uid_lookup_path=None):
    if not label_lookup_path:
      label_lookup_path = os.path.join(
          FLAGS.model_dir, 'imagenet_2012_challenge_label_map_proto.pbtxt')
    if not uid_lookup_path:
      uid_lookup_path = os.path.join(
          FLAGS.model_dir, 'imagenet_synset_to_human_label_map.txt')
    self.node_lookup = self.load(label_lookup_path, uid_lookup_path)

  def load(self, label_lookup_path, uid_lookup_path):
    """Loads a human readable English name for each softmax node.
    Args:
      label_lookup_path: string UID to integer node ID.
      uid_lookup_path: string UID to human-readable string.
    Returns:
      dict from integer node ID to human-readable string.
    """
    if not tf.gfile.Exists(uid_lookup_path):
      tf.logging.fatal('File does not exist %s', uid_lookup_path)
    if not tf.gfile.Exists(label_lookup_path):
      tf.logging.fatal('File does not exist %s', label_lookup_path)

    # Loads mapping from string UID to human-readable string
    proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()
    uid_to_human = {}
    p = re.compile(r'[n\d]*[ \S,]*')
    for line in proto_as_ascii_lines:
      parsed_items = p.findall(line)
      uid = parsed_items[0]
      human_string = parsed_items[2]
      uid_to_human[uid] = human_string

    # Loads mapping from string UID to integer node ID.
    node_id_to_uid = {}
    proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()
    for line in proto_as_ascii:
      if line.startswith('  target_class:'):
        target_class = int(line.split(': ')[1])
      if line.startswith('  target_class_string:'):
        target_class_string = line.split(': ')[1]
        node_id_to_uid[target_class] = target_class_string[1:-2]

    # Loads the final mapping of integer node ID to human-readable string
    node_id_to_name = {}
    for key, val in node_id_to_uid.items():
      if val not in uid_to_human:
        tf.logging.fatal('Failed to locate: %s', val)
      name = uid_to_human[val]
      node_id_to_name[key] = name

    return node_id_to_name

  def id_to_string(self, node_id):
    if node_id not in self.node_lookup:
      return ''
    return self.node_lookup[node_id]


def create_graph():
  """Creates a graph from saved GraphDef file and returns a saver."""
  # Creates graph from saved graph_def.pb.
  with tf.gfile.FastGFile(os.path.join(
      FLAGS.model_dir, 'classify_image_graph_def.pb'), 'rb') as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
    _ = tf.import_graph_def(graph_def, name='')


def run_inference_on_image(image):
  """Runs inference on an image.
  Args:
    image: Image file name.
  Returns:
    Nothing
  """
  if not tf.gfile.Exists(image):
    tf.logging.fatal('File does not exist %s', image)
  image_data = tf.gfile.FastGFile(image, 'rb').read()

  # Creates graph from saved GraphDef.
  create_graph()

  with tf.Session() as sess:
    # Some useful tensors:
    # 'softmax:0': A tensor containing the normalized prediction across
    #   1000 labels.
    # 'pool_3:0': A tensor containing the next-to-last layer containing 2048
    #   float description of the image.
    # 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG
    #   encoding of the image.
    # Runs the softmax tensor by feeding the image_data as input to the graph.
    softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
    predictions = sess.run(softmax_tensor,
                           {'DecodeJpeg/contents:0': image_data})
    predictions = np.squeeze(predictions)

    # Creates node ID --> English string lookup.
    node_lookup = NodeLookup()

    top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1]
    #for node_id in top_k:
    node_id = top_k[0]
    human_string = node_lookup.id_to_string(node_id)
    score = predictions[node_id]
    #  print('%s (score = %.5f)' % (human_string, score))
    #  print('%s %s' % (image, human_string))
    f = open( "test.txt", "a" )
    try:
      f.write( '%s %s\n' % (image, human_string))
    finally:
      f.close()

def maybe_download_and_extract():
  """Download and extract model tar file."""
  dest_directory = FLAGS.model_dir
  if not os.path.exists(dest_directory):
    os.makedirs(dest_directory)
  filename = DATA_URL.split('/')[-1]
  filepath = os.path.join(dest_directory, filename)
  if not os.path.exists(filepath):
    def _progress(count, block_size, total_size):
      sys.stdout.write('\r>> Downloading %s %.1f%%' % (
          filename, float(count * block_size) / float(total_size) * 100.0))
      sys.stdout.flush()
    filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)
    print()
    statinfo = os.stat(filepath)
    print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.')
  tarfile.open(filepath, 'r:gz').extractall(dest_directory)


def main(_):
  maybe_download_and_extract()
  image = (FLAGS.image_file if FLAGS.image_file else
           os.path.join(FLAGS.model_dir, 'cropped_panda.jpg'))
  run_inference_on_image(image)


if __name__ == '__main__':
  tf.app.run()

続いて、カメラキャプチャ用のコードも作成

camera.py

import time
import picamera

with picamera.PiCamera() as camera:
    camera.resolution = (1280, 960)
    camera.start_preview()
    time.sleep(2)
    camera.capture('image.jpg')

画像を細かく分けるコードも作成。

image_cut.py

from PIL import Image

im = Image.open("image.jpg")
w = im.size[0]
h = im.size[1]
rsize = min(w, h)
box = (0, 0, rsize, rsize)
region= im.crop(box)
subregion = list()
ds = float(rsize)/16.0
for i in xrange(16):
    wmin = int(ds*i)
    wmax = int(ds*(i+1))
    for j in xrange(16):
        k = 16*i + j
        hmin = int(ds*j)
        hmax = int(ds*(j+1))
        box = (wmin, hmin, wmax, hmax)
        subregion.append(region.crop(box))

for num in xrange(256):
    subregion[num].save(str(num)+'.jpg', "JPEG")

写真で撮っただけではゴキが小さすぎて認識できないため、画像を小分けにして画像認識させます。

今回の場合、16×16=256分割させてみました。

最後に、この3つのコードを動かすシェルスクリプトを作成。

image.sh

#!/bin/sh
rm test.txt
python camera.py
python image_cut.py
a=-1
while [ $a -ne 255 ]
do
  a=`expr $a + 1`
  python classify_image.py --image_file "${a}.jpg"
done

このスクリプトですが、

(1) Raspberry Piのカメラで撮影

(2) 画像を256分割

(3) その256分割した画像一つ一つを”classify_image.py”で画像分析

→ ”test.txt”というファイルに256個のファイルの画像認識結果が記録されます。

特に(3)の部分はわざわざシェルスクリプト上で256回繰り返すようになってますが。

中には”classify_image.py”の中で256回繰り返すように作ればよかったんじゃないか?と思う方もいるかもしれません。

実は最初、そういうコードを作ったんですが、なぜか4~5回目ループあたりでメモリオーバーを起こしてしまうため、こういう形にしました。

コマンドライン上で

$ chmod 777 image.sh

とし、実行形式に変えます。

これで準備完了。

さて、さっそくコードのテストですが

問題はどうやってテスト用のゴキを準備するか!?

我が家には今のところゴキが生息しておりません。

いや仮にいたとしてもわざわざ捕まえたくないですし。

てことで、こんな時は百均ショップ頼み。

Seriaでこんなものを買ってきました。

Img_0438

さすがは百均ショップ、何でもありますねぇ。

真ん中以外は要らないんですが、調子に乗って買ってきました。

Img_0441

こういう用途に使うためのもののようですが、まさか人工知能のテスト用に使うなどとは書いてませんね。

Img_0440

さて、迎え撃つはこのRaspberry Pi 3+メモスタンド。

このメモスタンド、カメラを支えるのにぴったり。これも百均にて購入。

Img_0443

いよいよRaspberry Pi vs Gの戦いの火ぶたが切って落とされます。

それにしても、なんともおぞましい光景ですねぇ。

Img_0444

こんな感じに、両面テープで張り付けておきました。

Tnsrflw_g01

Raspberry Pi 3のカメラではこんな感じ(実際は1280×960)。

これを256等分してくまなく探索。

で、出てきた結果がこちら。

画像認識した結果は、256等分された各画像ごと(0.jpg ~ 255.jpg)に”test.txt”という名前でリスト化されます。

ちなみにこのダミーゴキが写っているのは164番目の画像でしたが

Tensorflow_g01

cockroach」ではなく「isopod」(ワラジムシ科)として認識されてます。

・・・ちょっと違うけど気持ち悪い虫としては認識してくれたようです。

あとは、この気持ち悪い虫画像が出てきたときに、何らかのアクションを起こすコードに作り替えればいいだけ。

・・・なんですが、一つ大きな問題が

今回の1枚の画像(を256分割したもの)をスキャンするのに、なんと3時間以上かかりました

さすがに3時間かけて画像認識させているようではゴキさんに逃げられてしまいますね。

これは明らかに画像を分割させすぎ。

かといって4×4にしてしまうと、今度は画像中のゴキ君が小さくなりすぎて認識してくれません。

カメラをもっと近づけて狭い範囲をスキャンさせるようにすればいいんですが、6畳部屋の壁一面くらいはスキャンさせないとあんまり意味がなさそう。

ということで、OpenCVを使って画像の変化点をとらえて、狭い範囲を切り出して認識させるような仕組みにしないとだめそうです。

OpenCVで物体検出器を作成する① ~基礎知識~ - 技術者ブログ

てことで、今こちらのサイトで勉強中。

おぞましいものを買ってきたわりには、得られるものの少なかった今回のチャレンジ。

人工知能は一日にしてならずや、ですね。

さて、最終的には数秒でゴキを捕捉させ、ゴキが出現したらお知らせし、できれば自動で捕獲までできるようにしたいんですが。

その”捕獲させる手段”が思いつきません。

いいアイデアはないでしょうかね?

Raspberry Pi 3 本体+5V/2.5A USB電源アダプター+ケース+スイッチ付きケーブル+ヒートシンク 5点セット Raspberry Pi 3 Model B

« ファミコン・スーファミソフトが80本収録されたゲーム機”Retro-bit GENERATIONS” | トップページ | Intel以外のCPUがまだ熱かった90年代終わりのx86互換CPUたち »

Raspberry Pi・Arduino・電子工作」カテゴリの記事

コメント

初めまして。
かなり前の投稿のようなので、メッセージ届くか分かりませんが、拝見させて頂きました。  
探知機や、壁などに向かって当てると音で知らせてくれるようなそんな機械はないのかと、検索していたらあなたさまに辿り着きました。 

その後、作ってみたは如何でしょうか。
成功しましたでしょうか?よかったら教えて下さい。

> 匿名さん

ありがとうございます。結局、自宅でゴキブリが出てこないため、ゴキブリ探知機は作っておりませんが、もし今作るなら、という前提であれば、「物体検出」が使えると考えます。
例えば、Yolov4やSSDと呼ばれる物体検出手法を用い、Raspberry PiではなくJetson nanoの2GB版を使えば、かなり現実的な速度のゴキブリ探知機が作れそうだと言う感触があります。
ゴキではなく、人用ですが、最近はこんな物を作ってたりします。

https://arkouji.cocolog-nifty.com/blog/2021/06/post-d7eeb5.html

これを、ゴキブリ用に仕立てればいいだけです。
もっとも、ゴキブリを検出してくれる都合のいい物体検出用の学習器は世の中にはないため、たくさんのゴキブリ画像を集めて自分で作る必要が出てきますが……以前、ハチ撃退機を作ろうと思ってGoogle画像検索をして、心が折れそうになったことがあります。気持ち悪いですからね、昆虫の画像って。

この当時より、手法もハードも発達して、さらに私個人のスキルも上がっているため、やろうと思えばできるんですが、なぜかやろうとは思わなくなってしまい……飽きっぽい性格なので、いけませんね。

そもそも論になりますが、家の中で睡眠中に動き回るものはそうそう無いので、
人間以外の動くものに近づいてゴキジェットやゴキムエンダーをかける装置で十分なのではと個人的には思います。
ついでにその日の噴射回数をスマホに通知してくれると良いですね。

> ??さん
幸い我が家ではまだGが現れていないため、この手の仕掛けを設置することなく過ごせています。
この記事を書いてからもう5年以上経つので、今ならいろいろできそうです。物体検出手法を用いるまでもなく、仰るとおり背景差分から動くものとその大きさを特定して、虫サイズのものを察知すれ仕組みでもいけそうです。

コメントを書く

(ウェブ上には掲載しません)

トラックバック


この記事へのトラックバック一覧です: TensorFlowを使って”ゴキブリ”探知機を作ろうとしてみた:

« ファミコン・スーファミソフトが80本収録されたゲーム機”Retro-bit GENERATIONS” | トップページ | Intel以外のCPUがまだ熱かった90年代終わりのx86互換CPUたち »

無料ブログはココログ

スポンサード リンク

ブログ村