2019年5月21日火曜日

自作キーボード(ErgoDash mini)のファーム書き換えでエラー


自作キーボードのErgoDash miniを使わせてもらってるんだけど、ファーム書き換え時にエラー出て気持ちが萎えたので、覚書。
因みに、キーマップをここで作って、toolboxで焼くという、お手軽版でやっております。

まず、ダメなパターンとして、リセットボタンを押してもUSB接続が認識されません。
ls /dev/tty.*
/dev/tty.Bluetooth-Incoming-Port
これは、再起動などで回復するようです。
ls /dev/tty.*
/dev/tty.Bluetooth-Incoming-Port /dev/tty.usbmodem14101
次に、リセットボタンを押した際に、Bluetoothの方を認識してしまうパターンです。
*** Caterina device connected
    Found port: /dev/cu.Bluetooth-Incoming-Port
*** Attempting to flash, please don't remove device
>>> avrdude -p atmega32u4 -c avr109 -U flash:w:xxx.hex:i -P /dev/cu.Bluetooth-Incoming-Port -C avrdude.conf
    avrdude: warning at avrdude.conf:14976: part atmega32u4 overwrites previous definition avrdude.conf:11487.
    
    Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding
*** Caterina device disconnected
これは、なんていうか、何回かやってるとUSBを認識するので、すかさずFLASHです。(なんだそれ😄
*** Caterina device connected
    Found port: /dev/cu.usbmodem14101
*** Attempting to flash, please don't remove device
>>> avrdude -p atmega32u4 -c avr109 -U flash:w:/xxx.hex:i -P /dev/cu.usbmodem14101 -C avrdude.conf
    avrdude: warning at avrdude.conf:14976: part atmega32u4 overwrites previous definition avrdude.conf:11487.
    
    Connecting to programmer: .
    Found programmer: Id = "CATERIN"; type = S
        Software Version = 1.0; No Hardware Version given.
    Programmer supports auto addr increment.
    Programmer supports buffered memory access with buffersize=128 bytes.
    
    Programmer supports the following devices:
        Device code: 0x44
    
    avrdude: AVR device initialized and ready to accept instructions
    
    Reading | ################################################## | 100% 0.00s
    
    avrdude: Device signature = 0x1e9587
    avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
             To disable this feature, specify the -D option.
    avrdude: erasing chip
    avrdude: reading input file "/xxx.hex"
    avrdude: writing flash (15502 bytes):
    
    Writing | ################################################## | 100% 1.21s
    
    avrdude: 15502 bytes of flash written
    avrdude: verifying flash memory against /xxx.hex:
    avrdude: load data flash data from input file /xxx.hex:
    avrdude: input file /xxx.hex contains 15502 bytes
    avrdude: reading on-chip flash data:
    
    Reading | ################################################## | 100% 0.11s
    
    avrdude: verifying ...
    avrdude: 15502 bytes of flash verified
    
    avrdude done.  Thank you.
    
*** Caterina device disconnected
ちゃんと調べればなにかあるのかもしれませんが、解決策は「数撃ちゃ当たる戦法」でした。

ついでにキーマップを残しておきます。




2019年5月10日金曜日

Jetson Nano で MNISTをラズパイカメラから動かしてみる

あれから、MNIST関係色々見てました。
詳しいことはよくわからなかったけど、層をたくさん経由すると「deep」になるとのこと。
だから、前回のはディープラーニングではないようです。
とはいっても、根本的な意味はよくわかっていないので、今後の課題とします。
ざっくりとした理解だけれども、今回の教師あり学習に関して言えば、画像から分布を作って(学習)、その分布に当てはめて近い値が出たらそれが答えだ!的な感じっぽい。
ディープの部分は写経なんだけれども、学習データ保存して、読込して、カメラから画像取得して読み込んだ学習データに照らし合わせてリアルタイムに数字認識するプログラムを書いてみた。
参考にしたサイトのリンク貼っておきます。

http://blog.brainpad.co.jp/entry/2016/02/25/153000

https://qiita.com/JUN_NETWORKS/items/6514e017e89b9adbfb8d

https://qiita.com/tsutof/items/2d2248ec098c1b8d3e32

ソース見たほうが早いかな。

import tensorflow as tf
import numpy as np
import os,sys
import cv2
from PIL import Image, ImageEnhance,ImageDraw

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

def weight_variable(shape):
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

def conv2d(x, W):
  return tf.nn.conv2d(x,W,strides=[1, 1, 1, 1],padding='SAME')

def max_pool_2x2(x):
  return tf.nn.max_pool(x,ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1],padding='SAME')

x = tf.placeholder(tf.float32, shape=[None, 784])
y_ = tf.placeholder(tf.float32, shape=[None, 10])

# 画像をリシェイプ 第2引数は画像数(-1は元サイズを保存するように自動計算)、縦x横、チャネル
x_image = tf.reshape(x, [-1, 28, 28, 1])
print(x_image)

### 1層目 畳み込み層
# 畳み込み層のフィルタ重み、引数はパッチサイズ縦、パッチサイズ横、入力チャネル数、出力チャネル数
# 5x5フィルタで32チャネルを出力(入力は白黒画像なので1チャンネル)
W_conv1 = weight_variable([5, 5, 1, 32])
# 畳み込み層のバイアス
b_conv1 = bias_variable([32])
# 活性化関数ReLUでの畳み込み層を構築
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

### 2層目 プーリング層
# 2x2のマックスプーリング層を構築
h_pool1 = max_pool_2x2(h_conv1)

### 3層目 畳み込み層
# パッチサイズ縦、パッチサイズ横、入力チャネル、出力チャネル
# 5x5フィルタで64チャネルを出力
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

### 4層目 プーリング層
h_pool2 = max_pool_2x2(h_conv2)

### 5層目 全結合層
# オリジナル画像が28x28で、今回畳み込みでpadding='SAME'を指定しているため
# プーリングでのみ画像サイズが変わる。2x2プーリングで2x2でストライドも2x2なので
# 縦横ともに各層で半減する。そのため、28 / 2 / 2 = 7が現在の画像サイズ

# 全結合層にするために、1階テンソルに変形。画像サイズ縦と画像サイズ横とチャネル数の積の次元
# 出力は1024(この辺は決めです) あとはSoftmax Regressionと同じ
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])

h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

# ドロップアウトを指定
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

### 6層目 Softmax Regression層
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])

y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

### 訓練 ###
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))


saver = tf.train.Saver()

config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.gpu_options.visible_device_list="0"
with  tf.Session(config=config) as sess:
  sess.run(tf.initialize_all_variables())

  os.makedirs("./model_2",exist_ok=True)

  ckpt = tf.train.get_checkpoint_state('./model_2')
  if ckpt:
    saver.restore(sess, ckpt.model_checkpoint_path)
  else:
    for i in range(1500):
      batch = mnist.train.next_batch(50)
      if i%100 == 0:
        train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1],keep_prob: 1.0})
        print("step %d, training accuracy %g"%(i, train_accuracy))
      train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

    saver.save(sess, "./model_2/model.ckpt")

  num_test = len(mnist.test.labels)
  sum_accuracy = 0
  for i in range(0, num_test, 50):
    sum_accuracy = sum_accuracy + accuracy.eval(feed_dict={x: mnist.test.images[i:i+50], y_: mnist.test.labels[i:i+50], keep_prob: 1.0})
  print("test accuracy:", sum_accuracy/(num_test/50))


  GST_STR = 'nvarguscamerasrc \
      ! video/x-raw(memory:NVMM), width=320, height=240, format=(string)NV12, framerate=(fraction)10/1 \
      ! nvvidconv ! video/x-raw, width=(int)320, height=(int)240, format=(string)BGRx \
      ! videoconvert \
      ! appsink'
  WINDOW_NAME = 'Camera Test'

  cap = cv2.VideoCapture(GST_STR, cv2.CAP_GSTREAMER)

  while True:
    ret, img = cap.read()
    if ret != True:
      break

    pilImg = Image.fromarray(np.uint8(img))
    #print(pilImg.format, pilImg.size, pilImg.mode)
    img_width, img_height = pilImg.size
    draw = ImageDraw.Draw(pilImg)
    draw.rectangle(((img_width - 150) // 2,
                         (img_height - 150) // 2,
                         (img_width + 150) // 2,
                         (img_height + 150) // 2), outline=(255, 255, 255))

    mnistImg = Image.fromarray(np.uint8(img))
    mnistImg = mnistImg.crop(((img_width - 150) // 2,
                         (img_height - 150) // 2,
                         (img_width + 150) // 2,
                         (img_height + 150) // 2))
    mnistImg = mnistImg.convert("L")
    color = ImageEnhance.Color(mnistImg)
    mnistImg = color.enhance(1.5)
    contrast = ImageEnhance.Contrast(mnistImg)
    mnistImg = contrast.enhance(1.5)
    brightness = ImageEnhance.Brightness(mnistImg)
    mnistImg = brightness.enhance(1.5)
    sharpness = ImageEnhance.Sharpness(mnistImg)
    mnistImg = sharpness.enhance(1.5)
    mnistImg = mnistImg.resize((28, 28), Image.LANCZOS)
    #print(mnistImg)
    mnistImg = map(lambda x: 255 - x, mnistImg.getdata())
    mnistImg = np.fromiter(mnistImg, dtype=np.uint8)
    mnistImg = mnistImg.reshape(1, 784)
    mnistImg = mnistImg.astype(np.float32)
    mnistImg = np.multiply(mnistImg, 1.0 / 255.0)
    # print(mnistImg)
    for i in range(len(mnistImg[0])):
      num=mnistImg[0][i]
      if num<0.4:
        print('    ', end="")
      else:
        print('%03d ' % (num*1000), end="")
      if i % 28 == 0:
        print('\n')

    #学習データと読み込んだ数値との比較を行う
    pred = sess.run(y_conv, feed_dict={x:mnistImg, y_: [[0.0] * 10], keep_prob: 1.0})[0]
    # print(pred)
    if not np.max(pred) < 0.5 :
      print(np.argmax(pred) ,np.max(pred))
      draw.text((10,10),f'{np.argmax(pred)} {round(np.max(pred)*100,2)}%')


    imgArray = np.asarray(pilImg)
    cv2.imshow(WINDOW_NAME, imgArray)

    key = cv2.waitKey(10)
    if key == 27: # ESC 
      break
起動すると、ウインドウが開いてカメラの画像が出ます。
真ん中の白枠に手書きの文字を入れると、上に値が出るってわけ。
認識率悪くて、コントラスト上げたり、明度あげたり、色々やってみてる。
コンソールに、プログラムからみたテンソルを表示しています。

色々やってて思ったのが、Jetson Nanoだと、何するにしてもメモリ不足で死にます。
これは、僕の書き方の問題なのかもしれないけど、いろいろシンドかった。
学習するにしても、バッチサイズ減らしてやらないと落ちるし、学習データの読み込みでも、ブラウザは落としておかないと死ぬ。
こういったあたりも、今後調べていきたい。
次は、自分で教師データ作って学ばせてあげたい。
できるかな?