opencv チュートリアルチャレンジ7 Canny法によるエッジ検

Canny法によるエッジ検出 — OpenCV-Python Tutorials 1 documentation

cv2.Canny

void cv::Canny   (
    InputArray  image,
    OutputArray     edges,
    double  threshold1,
    double  threshold2,
    int     apertureSize = 3,
    bool    L2gradient = false 
)

image   8-bit input image.
edges   output edge map; single channels 8-bit image, which has the same size as image .
threshold1  first threshold for the hysteresis procedure.
threshold2  second threshold for the hysteresis procedure.
apertureSize    aperture size for the Sobel operator.
L2gradient  a flag, indicating whether a more accurate ....

やってみる

元画像 f:id:pongsuke:20170519145649j:plain

edges = cv2.Canny(img_gray, 50, 150, apertureSize=3)

f:id:pongsuke:20170519145721p:plain

edges = cv2.Canny(img_gray, 20, 100, apertureSize=3)

f:id:pongsuke:20170519150904p:plain

edges = cv2.Canny(img_gray, 50, 150, apertureSize=7)

f:id:pongsuke:20170519150912p:plain

keras-rl を試す

keras-rl を試します。

Git

github.com

インストー

$ sudo pip install keras
$ sudo pip install keras-rl

テスト

まず、サンプルプログラムを入手します。

$ git clone https://github.com/matthiasplappert/keras-rl.git

私は tensorflow を virtualenv で入れましたので、、、

$ cd tensorflow/
$ source ~/tensorflow/bin/activate
(tensorflow)$ python ~/github/keras-rl/examples/dqn_cartpole.py

を、コンソールから行います。

Chainer Linear を確認する

Chainer Linear を確認する

理解が進む度に、書き加えていく。

サンプルスクリプト

y = 2x + 2 を想定したもの。

#!/usr/bin/env python
# coding:utf-8
import numpy as np
import chainer.functions as F
import chainer.links as L
from chainer import Variable, optimizers

# モデル定義
model = L.Linear(1, 1)

optimizer = optimizers.SGD()
optimizer.setup(model)

# 学習させる回数
times   = 1000

# 入力ベクトル
x   = Variable(np.array( [[1],[3],[5],[7]], dtype=np.float32))
#x  = Variable(np.array( [[1]], dtype=np.float32))

# 正解ベクトル
t   = Variable(np.array( [[2],[6],[10],[14]], dtype=np.float32))
#t  = Variable(np.array( [[2]], dtype=np.float32))

# 学習ループ
for i in range(0, times):
    optimizer.zero_grads()  # 勾配を初期化
    y   = model(x)          # モデルに予測させる
    loss    = F.mean_squared_error(y, t) # 損失を計算
    print("Data: {}, Loss: {}".format(y.data, loss.data) )
    loss.backward()         # 逆伝播する
    optimizer.update()      # optimizer を更新する

print("Weight : {}".format(model.W.data) )
print("Bias   : {}".format(model.b.data) )

print("---TEST---")
x   = Variable(np.array( [[3],[4],[5]], dtype=np.float32) )
y   = model(x)

print("Test data   : {}".format(x.data) )
print("Test result : {}".format(y.data) )

実行

$ python 001.py 

 ・・・

Data: [[  3.98719549]
 [  7.99330425]
 [ 11.99941349]
 [ 16.00552177]], Loss: 5.99056111241e-05
Weight : [[ 2.00304031]]
Bias   : [ 1.98421395]
---TEST---
Test data   : [[ 3.]
 [ 4.]
 [ 5.]]
Test result : [[  7.99333477]
 [  9.99637508]
 [ 11.9994154 ]]

ということで、

y = 2.00304031 x + 1.98421395

と、作成されました!

ソースコード

/usr/local/lib/python2.7/dist-packages/chainer/links/connection/linear.py

/usr/local/lib/python2.7/dist-packages/chainer/functions/connection/linear.py

APIから

Linearモデル

コンスタント

class chainer.links.Linear(in_size, out_size, wscale=1, bias=0, nobias=False, initialW=None, initial_bias=None) とのこと。

今回は model = L.Linear(1, 1) として、 in_size=1, out_size=1 で作っている。

class Linear(link.Link): とのことで、link.Link を継承しているらしい。

call

model(x) すると、 __call__ が呼ばれるわけだけど、そのなかで

from chainer.functions.connection import linear
 ・・・
return linear.linear(x, self.W, self.b)

なので、結局のところ何をするのかは、 functions/connection/linear.py を見る。

def linear(x, W, b=None):
    if b is None:
        return LinearFunction()(x, W)
    else:
        return LinearFunction()(x, W, b)

コメントをカットしたらこうなった。

LinearFunction()(x, W) をみて、ぎょっとしたが、これは、LinearFunction インスタンスを作成して、その ___call___ を読んでいる。

class LinearFunction(function.Function): とのことなので、 Function をみよう。

/usr/local/lib/python2.7/dist-packages/chainer/function.py をみる。

class Function(object):
 ・・・
    def __call__(self, *inputs):
    """Applies forward propagation with chaining backward references.

とのこと。

cuda が使えるかどうかなどで条件分岐されているが、forward するんだろと思う。

forward

    def forward(self, inputs):
        x = _as_mat(inputs[0])
        W = inputs[1]
        y = x.dot(W.T).astype(x.dtype, copy=False)
        if len(inputs) == 3:
            b = inputs[2]
            y += b
        return y,

ドット演算(行列の積)している。

あてがうのは、 W.data.T なので、 transpose されたものだ。

検算

y = 2.00304031 x + 1.98421395

に、x=3, 4, 5 を入れてみると、たしかに、 7.99333477, 9.99637508, 11.9994154 になる。

Openai Gym を試す

OpenAI Gym

インストー

$ git clone https://github.com/openai/gym
$ cd gym
$ sudo pip install -e .

テスト

import gym
env = gym.make('CartPole-v0')
env.reset()
for _ in range(1000):
    env.render()
    env.step(env.action_space.sample()) # take a random action

なお、XRDPのリモートデスクトップ環境では再生できませんでした。

Tensorflow で Mnist

Tensorflow で Mnist をやってみます。

ドキュメント

MNIST For ML Beginners  |  TensorFlow

サンプルコード

tensorflow/mnist_softmax.py at r1.1 · tensorflow/tensorflow · GitHub

これを使えということなので、使ってみます。

mnist 用のデータを自動でダウンロードしてくれます。
Chainer 用に既にダウンロードしてありますが、まぁ、気にしません!

$ python mnist_softmax.py 
Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.
Extracting /tmp/tensorflow/mnist/input_data/train-images-idx3-ubyte.gz
Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.
Extracting /tmp/tensorflow/mnist/input_data/train-labels-idx1-ubyte.gz
Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.
Extracting /tmp/tensorflow/mnist/input_data/t10k-images-idx3-ubyte.gz
Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.
Extracting /tmp/tensorflow/mnist/input_data/t10k-labels-idx1-ubyte.gz
2017-05-09 15:08:44.979276: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-09 15:08:44.979344: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-09 15:08:45.215246: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:901] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2017-05-09 15:08:45.215956: I tensorflow/core/common_runtime/gpu/gpu_device.cc:887] Found device 0 with properties: 
name: GeForce GTX 1060 6GB
major: 6 minor: 1 memoryClockRate (GHz) 1.7845
pciBusID 0000:06:00.0
Total memory: 5.93GiB
Free memory: 5.84GiB
2017-05-09 15:08:45.215999: I tensorflow/core/common_runtime/gpu/gpu_device.cc:908] DMA: 0 
2017-05-09 15:08:45.216016: I tensorflow/core/common_runtime/gpu/gpu_device.cc:918] 0:   Y 
2017-05-09 15:08:45.216045: I tensorflow/core/common_runtime/gpu/gpu_device.cc:977] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 1060 6GB, pci bus id: 0000:06:00.0)
0.9186

ubuntu14.04 LTS + CUDA + cuDNN + Tensorflow インストールメモ

tensorflow の動作確認まで

tensorflow

www.tensorflow.org

インストールガイド

Installing TensorFlow on Ubuntu  |  TensorFlow

インストール方法は何種類か有るらしいですが、We recommend the virtualenv installation. とのことなので、素直に従います。

インストー

$ sudo apt-get install python-virtualenv
$ mkdir ~/tensorflow
$ virtualenv --system-site-packages ~/tensorflow
New python executable in ***/tensorflow/bin/python
Installing setuptools, pip...done.

$ source ~/tensorflow/bin/activate
(tensorflow)$ pip install --upgrade tensorflow-gpu

失敗するので・・・

(tensorflow)$ pip install --upgrade https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.1.0-cp27-none-linux_x86_64.whl

ログがいっぱい出て・・・

Successfully installed tensorflow-gpu mock numpy protobuf wheel werkzeug funcsigs pbr setuptools
Cleaning up...

インストールのチェック validate the installation.

(tensorflow)$ deactivate

$ source ~/tensorflow/bin/activate

(tensorflow)$ python
Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> hello = tf.constant('Hello, TensorFlow!')
>>> sess = tf.Session()
2017-05-09 15:00:35.019097: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-09 15:00:35.019149: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-05-09 15:00:35.339102: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:901] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2017-05-09 15:00:35.339812: I tensorflow/core/common_runtime/gpu/gpu_device.cc:887] Found device 0 with properties: 
name: GeForce GTX 1060 6GB
major: 6 minor: 1 memoryClockRate (GHz) 1.7845
pciBusID 0000:06:00.0
Total memory: 5.93GiB
Free memory: 5.84GiB
2017-05-09 15:00:35.339858: I tensorflow/core/common_runtime/gpu/gpu_device.cc:908] DMA: 0 
2017-05-09 15:00:35.339875: I tensorflow/core/common_runtime/gpu/gpu_device.cc:918] 0:   Y 
2017-05-09 15:00:35.339902: I tensorflow/core/common_runtime/gpu/gpu_device.cc:977] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 1060 6GB, pci bus id: 0000:06:00.0)
>>> print(sess.run(hello))
Hello, TensorFlow!
>>>

事前に鬼門である nvidia のドライバーと CUDA, cuDNN のインストールを済ませてあったので、すんなりと入ったようです。

tesseract-ocr その2 学習させてみる

まず、apt-get でインストールしても、training-tools が入っていません。

やむなく、コンパイルします。

また、依存関係の問題で、 tesseract-ocr 3.05 と leptonica-1.74.1 の組み合わせになりました。

tesseract-ocr 3.05 は Leptonica 1.74 or higher is required. なので必要でした。

Leptonica を準備する

まず、apt-get で入る Leptonica について。

$ sudo apt-cache policy libleptonica-dev
libleptonica-dev:
  インストールされているバージョン: 1.70.1-1
  候補:               1.70.1-1

です。

ソースからコンパイルですね。

http://www.leptonica.com/download.html

$ cd leptonica-1.74.1
$ ./configure
$ make
$ make install

tesseract-ocr を準備する

GitHub - tesseract-ocr/tesseract: Tesseract Open Source OCR Engine (main repository)

The latest stable version is 3.05.00, released in February 2017. とあるから、gitから 3.05 が入るんだろう。(間違い)

ソースをゲットして、展開してコンパイルする

$ git clone https://github.com/tesseract-ocr/tesseract.git
$ cd tesseract-ocr(だったかな?)
$ ./autogen.sh
$ ./configure --prefix=/usr/local/tesseract/
$ make
$ sudo make install
$ sudo ldconfig

training-toolsもコンパイルする

$ make training
$ sudo make training-install

PATH 通す

export TESSDATA_PREFIX=/usr/local/tesseract/share/
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

を、.bashrc などに足しておく。

バージョン確認
$ /usr/local/tesseract/bin/tesseract -v
tesseract 4.00.00alpha
 leptonica-1.74.1
  libjpeg 8d (libjpeg-turbo 1.3.0) : libpng 1.2.50 : libtiff 4.0.3 : zlib 1.2.8

 Found SSE

あれ??? 4.00.00 alpha がインストールされたぞ?最新バージョンは 4.00.00 だったらしい。

やり直し

$ wget https://github.com/tesseract-ocr/tesseract/archive/3.05.00.tar.gz -O tesseract-ocr.tar.gz
$ cd tesseract-3.05.00
$ ./autogen.sh
$ ./configure --prefix=/usr/local/tesseract/
$ make
$ sudo make install

$ sudo make install
$ sudo ldconfig

$ /usr/local/tesseract/bin/tesseract -v
tesseract 3.05.00
 leptonica-1.74.1
  libjpeg 8d (libjpeg-turbo 1.3.0) : libpng 1.2.50 : libtiff 4.0.3 : zlib 1.2.8

$ /usr/local/tesseract/bin/tesseract hw.png out -l eng
Tesseract Open Source OCR Engine v3.05.00 with Leptonica
kiyo@kiyo-PowerEdge-T410:~$ cat out.txt 
HeIIow world.

学習 jTessBoxEditor

jTessBoxEditor 起動

$ java -jar jTessBoxEditor.jar

簡単な手順

・"TIFF/Box Generator" タブから、Output の場所と、言語、フォントを設定し、Generate する。 ・Generate されたBOXは、"BOX Editor" タブでOpenすると確認できる。 ・"Trainer"タブから、Tesseract のPathを指定し、Training Data を指定して、RUN すると、指定したディレクトリに tessdata/***.traineddata が作成される。 ・***.traineddata を、tesseract の tessdata ディレクトリに入れる。

テスト

f:id:pongsuke:20170412153611p:plain

0123456789

f:id:pongsuke:20170412153616p:plain

7894561230

なお、上記2つは成功した例ですが、作成した学習データと、読ませるフォントが異なると上手に判定できません。