2018年9月6日木曜日

MNISTは「重心」が重要

scikit-learnの手書き数字認識で、MNISTのデータを使ってみることにした。
先ずは、どんな数字の画像データなのか現物確認しないと始まらないので、MNISTデータを
画像に落とすスクリプトを書いた。
どうせなら、先に作ったスクリプトで使えるファイル名で画像保存する。

"counter_limit"で各数字ごとに保存する件数を指定。
下の例だと、「0」1,000件、「1」1,000件、、、「9」1,000件、と合計10,000件の画像が保存される。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import numpy as np
from sklearn import datasets
import cv2, os

counter = [''] * 10
counter_limit = 1000

try:
    os.mkdir('mnist_img')
except:
    pass

for i in range (0, 10):
    counter[i] = 0
    try:
        os.mkdir(str(i) + 'test')
    except:
        continue


mnist = datasets.fetch_mldata('MNIST original')
X, Y = mnist.data,mnist.target

for i in range(0, 70000):
    for n in range(0, 10):
        if Y[i] == n:
            counter[n] += 1
            if counter[n] <= counter_limit:
                img =255 - X[i].reshape(28,28)
                #cv2.imshow('mnist', img)
                #k = cv2.waitKey()
                print('i = ' + str(i) + ', target = ' + str(Y[i]))

                save_name0 = './' + str(n) + 'test/' + str(counter[n] * 10 + n) + 'test.png'
                cv2.imwrite(save_name0, img)

                save_name1 = './mnist_img/' + str(counter[n] * 10 + n) + 'test.png'
                cv2.imwrite(save_name1, img)


因みに、70,000件全ての画像を保存するには"counter_limit"を(余裕を見て)"counter_limit = 8000"とかにする。
そうすると、各数字に以下の件数の画像が保存される。

0:6903
1:7877
2:6990
3:7141
4:6824
5:6313
6:6876
7:7293
8:6825
9:6958

さて、保存した画像を眺めると、書かれた数字はバラエティがあるように見えるが、意外と偏っていて、
描画領域については広範に描かれている訳ではなさそうだ。

例えば、
「7」は28x28の上部に余白が多い
「6」だと28x28の下部に余白が多い
「4」が右に寄っているように見える(縦棒が中心より右に書かれている傾向にあるから)
「9」も28x28の上部に余白がある
等々。
ちょっと見ただけでも上記のような偏り(傾向)が分かる。

ただ、これには訳がある。
MNISTを公開しているサイトに以下の記述がある。
the images were centered in a 28x28 image by computing the center of mass of the pixels, and translating the image so as to position this point at the center of the 28x28 field.
※次のページが参考になりました。ありがとうございます。
「自分の手書きデータをTensorFlowで予測する」
「MNISTを学習させたモデルの気持ちを調べる」

「重心」を計算して中央に配置したデータのため、重心が上にあるものは下に移動して
上部に余白ができる。

重心が下にあるものは上に移動して下部に余白ができる。
このデータで学習をした場合、同じ様に重心で移動したデータの検証ならば正解率が
上がるが、そうでないデータでは誤認識が生じやすくなる。

そこで、MNISTのデータで学習をする場合は、それに合わせて判定用データも加工する
スクリプトを書いてみた。
前「おまけのおまけ」スクリプト"mnist_img"ディレクトリに置き、引数に28を渡して
生成した「28x28.csv」を選択すると、MNISTデータでの学習を前提にして判定用データ
を加工する。
具体的には"def mnist_mod(img):"の部分がそれにあたる。
横方向の移動に関しては、重心が中央よりも右方向に行くようにしてある。
※追記1(2018/09/09 10:00)※
"def mnist_mod(img):"の重心移動方法を修正。
※追記2(2018/09/10 22:00)※
digits.csv用の前処理を追加したつもり。
※追記3(2018/09/12 20:10)※
縦横比が同じでないテスト用画像の読み込みに対応したつもり。
現状下の様に、パーツに分かれた数字は、重心を求めていないためMNISTの学習結果では、正常に判定できない。
※追記4(2018/09/14 20:30)※
パーツに分かれた数字の重心(と言うか画像の重心)を求めるように修正。

ある程度の調整は出きるが、、、。うーん、今一。
ちなみに分類機のパラメータは出鱈目なので悪しからず。

※追記5(2019/12/05 11:10)※
OpenCVのバージョンにより、findContoursの返り値の数が異なる事に対応(?)。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
import numpy as np
import cv2
from time import sleep
from os.path import dirname, join, basename, exists
from sklearn.datasets.base import Bunch
import sys
from sklearn.externals import joblib

py_version = sys.version_info.major
cv_version = cv2.__version__[0:1]
module_path = dirname(__file__)

if py_version != 2:
    import tkinter as tk, tkinter.filedialog as tkfiledialog, tkinter.messagebox as tkmessage, \
           tkinter.simpledialog as tksimpledialog
else:
    import Tkinter as tk, tkFileDialog  as tkfiledialog, tkMessageBox as tkmessage, \
           tkSimpleDialog as tksimpledialog

def clf_select():
    def check():
        root.quit()
        return v.get()

    root = tk.Tk()
    root.title('digit_test')

    v = tk.IntVar()
    v.set(0)

    radio1 = tk.Radiobutton(text='SVM', variable=v, value=1, font=("",14))
    radio1.pack(anchor='w')

    radio2 = tk.Radiobutton(text='MLPClassifier', variable=v, value=2, font=("",14))
    radio2.pack(anchor='w')

    radio3 = tk.Radiobutton(text='LogisticRegression', variable=v, value=3, font=("",14))
    radio3.pack(anchor='w')

    radio4 = tk.Radiobutton(text='DecisionTreeClassifier', variable=v, value=4, font=("",14))
    radio4.pack(anchor='w')

    button1 = tk.Button(root, text='決 定', command= lambda: check(), width=30, font=("",14))
    button1.pack()

    root.mainloop()
    try:
        root.destroy()
    except:
        sys.exit()

    return check()

def csv_select():
    root = tk.Tk()
    root.withdraw()

    file_type = [('', '*csv')]
    data_path = join(dirname(__file__), 'data')
    tkmessage.showinfo('digit_test', 'データ(csv)を選択してください')
    test_csv = tkfiledialog.askopenfilename(filetypes=file_type, initialdir=data_path)
    if test_csv == () or test_csv == '':
        test_csv = 'digits.csv'
    else:
        test_csv = basename(test_csv)

    root.destroy()
    print(test_csv)
    return test_csv

def img_select():
    root = tk.Tk()
    root.withdraw()

    file_type = [('', '*png')]
    data_path = dirname(__file__)
    #tkmessage.showinfo(test_csv, '画像(png)を選択してください')
    test_img = tkfiledialog.askopenfilename(filetypes=file_type, initialdir=data_path)
    if test_img == () or test_img == '':
        test_img = 'digit_test.png'

    root.destroy()
    print(test_img)
    return test_img

def question0():
    root = tk.Tk()
    root.withdraw()

    y_or_n = tkmessage.askquestion(test_csv, '判定は' + str(predicted) + '\n正しいですか?')

    root.destroy()
    return y_or_n

def question1():
    root = tk.Tk()
    root.withdraw()

    next_y_or_n = tkmessage.askquestion(test_csv, '続けますか?')

    root.destroy()
    return next_y_or_n

def correct_input():
    root = tk.Tk()
    root.withdraw()
    root.after(1, lambda: root.focus_force())
    correct_digit = tksimpledialog.askinteger(test_csv, '正解を教えてください', 
                                              initialvalue='ここに入力',parent=root)

    root.destroy()
    return correct_digit

def load_digits():
    module_path = dirname(__file__)
    data = np.loadtxt(join(module_path, 'data', test_csv),
                      delimiter=',')

    data_len = int(np.sqrt(len(data[0]) - 1))

    target = data[:, -1].astype(np.int)
    flat_data = data[:, :-1]
    images = flat_data.view()
    images.shape = (-1, data_len, data_len)

    return Bunch(data=flat_data,
                 target=target,
                 target_names=np.arange(10),
                 images=images)

def pre_mod(img):
    data_len = int(np.sqrt(len(data[0])))
    size = (data_len, data_len)
    temp_h, temp_w = img.shape[:2]

    if temp_w > temp_h:
        temp_size = temp_w
    else:
        temp_size = temp_h

    if test_csv == '28x28.csv':
        temp_scale = 0.79
    elif test_csv == 'digits.csv':
        temp_scale = 1
    else:
        temp_scale = 0.9

    temp_re_size = temp_size + 2

    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img = np.round(255 - img)
    M = np.float32([[1,0,1],[0,1,1]])
    img = cv2.warpAffine(img, M, (temp_re_size, temp_re_size))
    img = np.round(255 - img)

    ret,thresh = cv2.threshold(img, 50, 255, 0)
    if cv_version == '3':
        imgEdge,contours,hierarchy = cv2.findContours(thresh, cv2.RETR_LIST,
                                                      cv2.CHAIN_APPROX_SIMPLE)
    else:
        contours,hierarchy = cv2.findContours(thresh, cv2.RETR_LIST,
                                              cv2.CHAIN_APPROX_SIMPLE)

    x_locale = []
    y_locale = []
    if len(contours) > 2:
        n = len(contours) - 1
    else:
        n = 1

    for i in range(0, n):
        x,y,w,h = cv2.boundingRect(contours[i])
        x_locale.append(x)
        x_locale.append(x + w)
        y_locale.append(y)
        y_locale.append(y + h)
    x = min(x_locale)
    y = min(y_locale)
    w = max(x_locale) - min(x_locale)
    h = max(y_locale) - min(y_locale)
    img = img[y:y+h, x:x+w]

    if h >= w:
        r_scale_x = int(w * data_len * temp_scale / h)
        r_scale_y = int(data_len * temp_scale)
    else:
        r_scale_x = int(data_len * temp_scale)
        r_scale_y = int(h * data_len * temp_scale / w)

    img = cv2.resize(img, (r_scale_x, r_scale_y), interpolation=cv2.INTER_AREA)
    img = np.round(255 - img)

    if test_csv == '28x28.csv':
        M = np.float32([[1,0,1],[0,1,1]])
        img = cv2.warpAffine(img, M, (r_scale_x + 2, r_scale_y + 2))

        M = cv2.moments(img)
        cx = int(M['m10']/M['m00']) + 1
        cy = int(M['m01']/M['m00']) + 1

    else:
        cx = int(r_scale_x / 2)
        cy = int(r_scale_y / 2)

    print(cx, cy)

    xc = int(data_len / 2) - cx
    yc = int(data_len / 2) - cy
    print(xc, yc)
    M = np.float32([[1,0,xc],[0,1,yc]])
    img = cv2.warpAffine(img, M, size)
    img = np.round(img / 16)
    return img


test_clf = clf_select()
if test_clf == 1:
    print('SVM')
    from sklearn import svm
    clf_name = 'svm'
    classifier = svm.SVC(C=10, gamma='scale')
elif test_clf == 2:
    print('MLPClassifier')
    from sklearn.neural_network import MLPClassifier
    clf_name = 'mlp'
    classifier = MLPClassifier(hidden_layer_sizes=(256, 128, 64, 64, 10),
                               verbose=True, alpha=0.001,
                               max_iter=10000, tol=0.00001, random_state=1)
elif test_clf == 3:
    print('LogisticRegression')
    from sklearn.linear_model import LogisticRegression
    clf_name = 'lr'
    classifier = LogisticRegression()
elif test_clf == 4:
    print('DecisionTreeClassifier')
    from sklearn.tree import DecisionTreeClassifier
    clf_name = 'dt'
    classifier = DecisionTreeClassifier()
else:
    sys.exit()

test_csv = csv_select()
test_img = img_select()

if exists('./' + test_csv + '.' + clf_name + '.pkl'):
    y_or_n = ''
    #y_or_n = 'no'
else:
    y_or_n = 'no'

while(True):
    digits = load_digits()
    n_samples = len(digits.images)
    data = digits.images.reshape((n_samples, -1))

    if y_or_n == 'no':
        print(classifier)
        classifier.fit(data, digits.target)
        joblib.dump(classifier, test_csv + '.' + clf_name + '.pkl', compress=True)
    else:
        classifier = joblib.load(test_csv + '.' + clf_name + '.pkl')

    images_and_labels = list(zip(digits.images, digits.target))
    for index, (image, label) in enumerate(images_and_labels[:10]):
        plt.subplot(3, 5, index + 1)
        plt.axis('on')
        plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
        plt.title('Training %i' % label)

    img = cv2.imread(test_img)
    grayim = pre_mod(img)
    im = grayim

    print(grayim)
    grayim = grayim.reshape(1, -1)
    np.savetxt('digit_test.csv', grayim, delimiter = ',', fmt = '%.0f')

    predicted = classifier.predict(grayim)
    print('判定は、' + str(predicted))

    plt.subplot(3, 5, 11)
    plt.axis('on')
    plt.imshow(img, cmap=plt.cm.gray_r, interpolation='nearest')
    plt.title('Original')
    plt.subplot(3, 5, 12)
    plt.axis('on')
    plt.imshow(im, cmap=plt.cm.gray_r, interpolation='nearest')
    plt.title('Prodicted %i' % predicted)
    plt.show()

    y_or_n = question0()

    if y_or_n == 'no':
        correct_digit = correct_input()
        if correct_digit != None:
            grayim = np.append(grayim, correct_digit)
            grayim = grayim.reshape(1, -1)

            f = open(join(module_path, 'data', test_csv), 'a')
            np.savetxt(f, grayim, delimiter = ',', fmt = '%.0f')
            f.close()
            sleep(1)
        else:
            correct_digit = str(predicted[0])
    else:
        next_y_or_n = question1()

        if next_y_or_n == 'no':
            sys.exit()

        test_img = img_select()


2018年8月20日月曜日

scikit-learn おまけの話(おまけ付き)

scikit-learn付属のdigits.csvを使ってみたが、手書き数字の認識をしたいなら、別のデザインの方が良いだろう。

「手書き数字の認識 → scikit-learn」ではなくて、「scikit-learnの演習 → 手書き数字の認識例を使用」
である事を忘れると、勘違いが生じる。

と、書きながらも勘違いのスクリプトをあげる。
前回と同じ動作の、scikit-learnを使った数字認識のスクリプトだが、tkinterを使ってみた。
データのcsvファイルの選択、判定する画像pngファイルの選択ダイアログやメッセージ等がtkinterで表示される。

※追記1(2018/08/21 14:30)※
分類器を保存するようにした。
スクリプトでは分類器の保存ファイルが存在すれば、それを使うようにしているが、
実際問題としては意味が無い

※追記2(2018/08/26 9:30)※
「8x8=64 + ラベル」以外に対応するようにした。
(画像の)縦横比が同じトレーニング用データならば、それに合わせてテスト用画像を
リサイズして判定する。
分類器の保存ファイルは実際の判定では使わないように変更。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.neural_network import MLPClassifier

import numpy as np
import cv2
from time import sleep
from os.path import dirname, join, basename, exists
from sklearn.datasets.base import Bunch
import sys
from sklearn.externals import joblib

py_version = sys.version_info.major

module_path = dirname(__file__)
#print(dirname(abspath('__file__')))
#print(module_path)

if py_version != 2:
    import tkinter as tk, tkinter.filedialog as tkfiledialog, tkinter.messagebox as tkmessage, \
           tkinter.simpledialog as tksimpledialog
else:
    import Tkinter as tk, tkFileDialog  as tkfiledialog, tkMessageBox as tkmessage, \
           tkSimpleDialog as tksimpledialog

def csv_select():
    root = tk.Tk()
    root.withdraw()

    file_type = [('', '*csv')]
    data_path = join(dirname(__file__), 'data')
    tkmessage.showinfo('digit_test', 'データ(csv)を選択してください')
    test_csv = tkfiledialog.askopenfilename(filetypes=file_type, initialdir=data_path)
    if test_csv == () or test_csv == '':
        test_csv = 'digits.csv'
    else:
        test_csv = basename(test_csv)

    root.destroy()
    #print(test_csv)
    return test_csv

def img_select():
    root = tk.Tk()
    root.withdraw()

    file_type = [('', '*png')]
    #data_path = dirname(abspath('__file__'))
    data_path = dirname(__file__)
    tkmessage.showinfo(test_csv, '画像(png)を選択してください')
    test_img = tkfiledialog.askopenfilename(filetypes=file_type, initialdir=data_path)
    #print(dirname(abspath('__file__')))
    if test_img == () or test_img == '':
        test_img = 'digit_test.png'

    root.destroy()
    #print(test_img)
    return test_img

def question0():
    root = tk.Tk()
    root.withdraw()

    y_or_n = tkmessage.askquestion(test_csv, '判定は' + str(predicted) + '\n正しいですか?')

    root.destroy()
    return y_or_n

def question1():
    root = tk.Tk()
    root.withdraw()

    next_y_or_n = tkmessage.askquestion(test_csv, '続けますか?')

    root.destroy()
    return next_y_or_n

def correct_input():
    root = tk.Tk()
    root.withdraw()
    root.after(1, lambda: root.focus_force())
    correct_digit = tksimpledialog.askinteger(test_csv, '正解を教えてください', 
                                              initialvalue='ここに入力',parent=root)

    root.destroy()
    return correct_digit

def load_digits():
    module_path = dirname(__file__)
    data = np.loadtxt(join(module_path, 'data', test_csv),
                      delimiter=',')

    data_len = int(np.sqrt(len(data[0]) - 1))
    #print(data_len)

    target = data[:, -1].astype(np.int)
    flat_data = data[:, :-1]
    images = flat_data.view()
    images.shape = (-1, data_len, data_len)

    return Bunch(data=flat_data,
                 target=target,
                 target_names=np.arange(10),
                 images=images)


test_csv = csv_select()
test_img = img_select()

if exists('./' + test_csv + '.mlp.pkl'):
    #y_or_n = ''
    y_or_n = 'no'
else:
    y_or_n = 'no'

while(True):
    digits = load_digits()
    n_samples = len(digits.images)
    data = digits.images.reshape((n_samples, -1))

    if y_or_n == 'no':
        classifier = MLPClassifier(hidden_layer_sizes=(100, 100, 100, 10),
                                   max_iter=10000, tol=0.00001, random_state=1)
        print(classifier)
        classifier.fit(data, digits.target)
        joblib.dump(classifier, test_csv + '.mlp.pkl', compress=True)
    else:
        classifier = joblib.load(test_csv + '.mlp.pkl')
        #print(classifier)

    images_and_labels = list(zip(digits.images, digits.target))
    #plt.figure(figsize=(5.5, 3))
    for index, (image, label) in enumerate(images_and_labels[:10]):
        plt.subplot(3, 5, index + 1)
        plt.axis('off')
        plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
        plt.title('Training %i' % label)

    img = cv2.imread(test_img)

    data_len = int(np.sqrt(len(data[0])))
    #print(data_len)

    size = (data_len, data_len)
    im = cv2.resize(img, size, interpolation=cv2.INTER_AREA)

    imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    #print(imgray)
    grayim = np.round((255 - imgray) / 16)
    grayim = grayim.reshape(1, -1)
    print(grayim)
    np.savetxt('digit_test.csv', grayim, delimiter = ',', fmt = '%.0f')

    predicted = classifier.predict(grayim)
    print('判定は、' + str(predicted))

    plt.subplot(3, 5, 11)
    plt.axis('off')
    plt.imshow(img, cmap=plt.cm.gray_r, interpolation='nearest')
    plt.title('Original')
    plt.subplot(3, 5, 12)
    plt.axis('off')
    plt.imshow(im, cmap=plt.cm.gray_r, interpolation='nearest')
    plt.title('Prodicted %i' % predicted)
    plt.show()

    y_or_n = question0()

    if y_or_n == 'no':
        correct_digit = correct_input()
        if correct_digit != None:
            grayim = np.append(grayim, correct_digit)
            #print(grayim)
            grayim = grayim.reshape(1, -1)

            f = open(join(module_path, 'data', test_csv), 'a')
            np.savetxt(f, grayim, delimiter = ',', fmt = '%.0f')
            f.close()
            sleep(1)
        else:
            correct_digit = str(predicted[0])
    else:
        next_y_or_n = question1()

        if next_y_or_n == 'no':
            break

        test_img = img_select()


おまけのおまけスクリプト

10個の画像から、トレーニング用csvデータを生成するスクリプト。
スクリプトと同一ディレクトリ内の「0test.png」「1test.png」・・・「9test.png」という
ファイル名の画像ファイルを、順番に読込み「8x8=64 + ラベル」の型でcsvファイルを生成する。
デフォルトでは8x8=64だが、スクリプトの引数に数値を与えるとそれを基にしたデータになる。
例えば、「5」を引数にすると、「5x5=25 + ラベル」の型になる。
(仮にスクリプトのファイル名を「prepare.py」とした場合、「python prepare.py 5」と言った記述)

生成されたcsvは、「5x5.csv」と言うファイル名で同一ディレクトリに保存される。
これをdataディレクトリへ移動して上のスクリプトで読み込めば、そのデータで分類器を生成してテスト
画像を判定する。

※追記3(2018/08/27 11:45)※
ファイル名からラベルの取り方を変更

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import numpy as np
import sys, cv2

args = sys.argv
print(args)
if len(args) > 2:
    print('引数が多すぎます')
    sys.exit()
elif len(args) == 2:
    try:
        type(int(args[1])) == int
        pix = int(args[1])
    except ValueError:
        print('引数の型が違います')
        sys.exit()
else:
    print('既定のデータ型を使います')
    pix = 8

for num in range(0, 10):
    try:
        img_file = str(num) + 'test.png'
        im = cv2.imread(img_file)

        size = (pix, pix)
        im = cv2.resize(im, size, interpolation=cv2.INTER_AREA)

        imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
        print(imgray)
        grayim = np.round((255 - imgray) / 16)
        grayim = grayim.reshape(1, -1)
        grayim = np.array(grayim, dtype = np.uint8)
        grayim = np.append(grayim, int(str(num)[-1]))
        grayim = grayim.reshape(1, -1)
        print(grayim)

        f = open(str(pix) + 'x' + str(pix) + '.csv', 'a')
        np.savetxt(f, grayim, delimiter = ",", fmt = "%.0f")
        f.close()

        #cv2.imshow(str(pix) + 'test', imgray)
        #cv2.waitKey(0)
    except:
        print(str(num) + 'test.png をスキップ')


10個より多くのデータを生成したい場合は"range(0, 10)"を書き換える
for num in range(0, 1000):

2018年8月4日土曜日

scikit-learnで漢数字認識


scikit-learnにサンプルで付いてくる手書き数字認識のデータセットを弄ってみるのが目的。
(※画像の処理にOpenCVを使ってます※)
手書き数字のデータ(digits.csv)を書き換えたいので、付属のデータをコピーして使用する。
"pip"でscikit-learnをインストールした私の環境で、データは以下のディレクトリにある。

※Windowsの場合
"C:/Users/<username>/AppData/Local/Programs/Python/Python36-32/lib/site-packages/sklearn/datasets/data/digits.csv.gz"

※Arch Linux 32の場合
"/usr/lib/python3.6/site-packages/sklearn/datasets/data/digits.csv.gz"

予め任意のディレクトリを作成してその中に"data"ディレクトリを作成し、その"data"ディレクトリに
"digits.csv.gz"をコピーする。更にエディタ等で直接扱いたいので、解凍もしておく。
データを置いたディレクトリより一つ上の階層に以下のPythonスクリプトを置く。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
from sklearn import datasets, svm

import numpy as np
import cv2
from time import sleep
from os.path import dirname, join
from sklearn.datasets.base import Bunch
import sys

y_or_n = 'n'
module_path = dirname(__file__)

def load_digits(n_class=10, return_X_y=False):
    module_path = dirname(__file__)
    data = np.loadtxt(join(module_path, 'data', 'digits.csv'),
                      delimiter=',')
    #with open(join(module_path, 'descr', 'digits.rst')) as f:
    #    descr = f.read()
    target = data[:, -1].astype(np.int)
    flat_data = data[:, :-1]
    images = flat_data.view()
    images.shape = (-1, 8, 8)

    if n_class < 10:
        idx = target < n_class
        flat_data, target = flat_data[idx], target[idx]
        images = images[idx]

    if return_X_y:
        return flat_data, target

    return Bunch(data=flat_data,
                 target=target,
                 target_names=np.arange(10),
                 images=images)
                 #DESCR=descr)


while(True):
    if y_or_n == 'n':
        digits = load_digits()

        n_samples = len(digits.images)
        data = digits.images.reshape((n_samples, -1))

        classifier = svm.SVC(C=100, gamma=0.001)
        print(classifier)
        #classifier.fit(data[:n_samples], digits.target[:n_samples])
        classifier.fit(data, digits.target)

    images_and_labels = list(zip(digits.images, digits.target))
    for index, (image, label) in enumerate(images_and_labels[:10]):
        plt.subplot(3, 5, index + 1)
        plt.axis('off')
        plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
        plt.title('Training %i' % label)

    img = cv2.imread('digit_test.png')

    size = (8, 8)
    im = cv2.resize(img, size, interpolation=cv2.INTER_AREA)

    imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    #print(imgray)
    grayim = np.round((255 - imgray) / 16)
    grayim = grayim.reshape(1, -1)
    print(grayim)
    np.savetxt('digit_test.csv', grayim, delimiter = ',', fmt = '%.0f')

    predicted = classifier.predict(grayim)
    print('判定は、' + str(predicted))

    plt.subplot(3, 5, 11)
    plt.axis('off')
    plt.imshow(img, cmap=plt.cm.gray_r, interpolation='nearest')
    plt.title('Original')
    plt.subplot(3, 5, 12)
    plt.axis('off')
    plt.imshow(im, cmap=plt.cm.gray_r, interpolation='nearest')
    plt.title('Prodicted %i' % predicted)
    plt.show()

    if sys.version_info.major != 2:
        y_or_n = input('正しいですか?(y or n)')
    else:
        y_or_n = raw_input('正しいですか?(y or n)')

    if y_or_n == 'n':
        correct_digit = input('正しい数字を教えてください:')

        grayim = np.append(grayim, int(correct_digit))
        grayim = grayim.reshape(1, -1)

        f = open(join(module_path, 'data', 'digits.csv'), 'a')
        np.savetxt(f, grayim, delimiter = ',', fmt = '%.0f')
        f.close()
        sleep(0.5)
    else:
        if sys.version_info.major != 2:
            next_y_or_n = input('続けますか?(y or n)')
        else:
            next_y_or_n = raw_input('続けますか?(y or n)')

        if next_y_or_n == 'n':
            break

"digits.csv"には8x8のサイズで0~9の数字の画像データを、0~16の階調で格納し、最後にその画像が
示す数字の正解ラベルが付加されている。
 1行に64個(8x8)の値と、1個の正解ラベルで、65個の値を持ち、全部で1796行になる。
「scikit-learn 手書き 数字」等で検索すると、1796のデータを学習用と分類用に分けて、その結果を
 示すサンプルが多く見受けられる。
このスクリプトでは、"digits.csv"のデータをすべて読み込んでサポートベクトルマシンによる分類器を
用意し、同じディレクトリ内の画像データ"digit_test.png"を読み込んで分類器を使った判定を行う。

画像"digit_test.png"は8x8ピクセルである必要はなく、例えば100x100でも良いし、80x100とかでも
8x8へ変換するようになっている。

スクリプトを実行させると、10個の凡例と手書き画像のオリジナル・8x8変換後の判定が表示される。


一旦その表示ウィンドウを閉じると、「正しいですか?」と聞いてくるので答えを入力する。


「n」を入力すると、「正しい数字を教えてください」と聞いてくるので正解を入力する。
読み込んだデータに正解ラベルを付加した状態でデータに追加し、再度分類器を生成して判定を やり直す。
一度で駄目でも、何回か繰り返せば正解の判定を導き出すようになる。
「続けますか?」に答える前に、次に判定したい画像を"digit_test.png"として用意しておけば、
新たな画像を判定する。でないと、同じ画像の判定を繰り返すだけになるので注意。

 ただ重要なのは、数字を理解して判定している訳ではなく、64個の値の組み合わせに正解を
紐付けているだけだと言うこと。

だから、アラビア数字じゃなく漢数字の画像データでも良いはず!

漢数字の画像を用意して、データの追加を何回か繰り替えして行けば、漢数字での判定が出きるようになる。

 (要は、正解ラベルで意味づけをしているのは人間なので、数字である必要も、画像データである必要も無い)  

おまけ(漢数字用データ)
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,6,6,6,6,8,8,0,3,4,4,4,4,2,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0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
0,0,0,5,0,0,0,0,0,0,0,11,0,0,0,0,0,2,8,13,12,10,0,0,0,0,8,6,7,4,0,0,0,0,11,0,8,2,0,0,0,2,10,0,6,7,0,7,0,8,4,0,0,9,11,7,0,1,0,0,0,0,0,0,9


MLPClassifier使用版
※追記1(2018/08/14 16:20)※
Python2にも対応したつもり
※追記2(2018/08/14 19:40)※
バグ取り

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.neural_network import MLPClassifier

import numpy as np
import cv2
from time import sleep
from os.path import dirname, join
from sklearn.datasets.base import Bunch
import sys

y_or_n = 'n'
module_path = dirname(__file__)

def load_digits():
    module_path = dirname(__file__)
    data = np.loadtxt(join(module_path, 'data', 'digits.csv'),
                      delimiter=',')

    target = data[:, -1].astype(np.int)
    flat_data = data[:, :-1]
    images = flat_data.view()
    images.shape = (-1, 8, 8)

    return Bunch(data=flat_data,
                 target=target,
                 target_names=np.arange(10),
                 images=images)


while(True):
    if y_or_n == 'n':
        digits = load_digits()
        n_samples = len(digits.images)
        data = digits.images.reshape((n_samples, -1))

        classifier = MLPClassifier(hidden_layer_sizes=(100, 100, 100, 10), max_iter=10000, tol=0.00001, random_state=1)
        print(classifier)
        classifier.fit(data, digits.target)

    images_and_labels = list(zip(digits.images, digits.target))
    for index, (image, label) in enumerate(images_and_labels[:10]):
        plt.subplot(3, 5, index + 1)
        plt.axis('off')
        plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
        plt.title('Training %i' % label)

    img = cv2.imread('digit_test.png')

    size = (8, 8)
    im = cv2.resize(img, size, interpolation=cv2.INTER_AREA)

    imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    #print(imgray)
    grayim = np.round((255 - imgray) / 16)
    grayim = grayim.reshape(1, -1)
    print(grayim)
    np.savetxt('digit_test.csv', grayim, delimiter = ',', fmt = '%.0f')

    predicted = classifier.predict(grayim)
    print('判定は、' + str(predicted))

    plt.subplot(3, 5, 11)
    plt.axis('off')
    plt.imshow(img, cmap=plt.cm.gray_r, interpolation='nearest')
    plt.title('Original')
    plt.subplot(3, 5, 12)
    plt.axis('off')
    plt.imshow(im, cmap=plt.cm.gray_r, interpolation='nearest')
    plt.title('Prodicted %i' % predicted)
    plt.show()

    if sys.version_info.major != 2:
        y_or_n = input('正しいですか?(y or n)')
    else:
        y_or_n = raw_input('正しいですか?(y or n)')

    if y_or_n == 'n':
        correct_digit = input('正しい数字を教えてください:')

        grayim = np.append(grayim, int(correct_digit))
        #print(grayim)
        grayim = grayim.reshape(1, -1)

        f = open(join(module_path, 'data', 'digits.csv'), 'a')
        np.savetxt(f, grayim, delimiter = ',', fmt = '%.0f')
        f.close()
        sleep(1)
    else:
        if sys.version_info.major != 2:
            next_y_or_n = input('続けますか?(y or n)')
        else:
            next_y_or_n = raw_input('続けますか?(y or n)')

        if next_y_or_n == 'n':
            break

2018年5月3日木曜日

ServoBlaster が更新されました

去年こちらに書いたServoBlasterの問題が修正されていました。

 https://github.com/richardghirst/PiBits/tree/master/ServoBlaster

kernel 4.9以降に"/proc/cpuinfo"の"Hardware"情報を元に"board_model"を判定する方法
(実際は、"board_model"からgpioのベースになるアドレスを設定する方法)に不具合が
出ていましたが、こちらの"bcm_host_get_peripheral_address()" を使う方法になっています。

手持ちのRespberry Pi 2 Model Bでの動作確認ができました。

2018年2月17日土曜日

OpenCVで遊ぶ

OpenCVのテンプレートマッチングを少し試していて思いついた。
テンプレートの検出画面をターゲティングモニタ風にしてみた。

2018年2月11日日曜日

動画でOpenCV(テンプレートマッチング)

WebカメラLogicool c270を買ったので 「OpenCVのテンプレートマッチングを試す 」
動画でやってみた。

今回は、OpenCVのチュートリアル「動画を扱う」を参考にした。


テンプレート画像として、"temp100.png" "temp200.png" "temp300.png"を用意。
Logicool c270から読み込んだ画像を処理する。
Raspberry Pi 2 Model Bの処理を考えて、サイズを320x240、フレームレート15を設定。

※注意※
自分の環境では1回目の実行は問題ないが、2回目の実行で"cap = cv2.VideoCapture(0)"が
正常に行われないようなので、"cap.get(cv2.CAP_PROP_FPS) == 0"で判定しながら
繰り返し処理を入れてあります。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import cv2
import numpy as np
import tkinter

cap = cv2.VideoCapture(0)

while(cap.get(cv2.CAP_PROP_FPS) == 0):
    cap.release()
    cap = cv2.VideoCapture(0)

cap.set(3, 320)
cap.set(4, 240)
cap.set(5, 15.0)

print(cap.get(3))
print(cap.get(4))
print(cap.get(5))

grid_x = (25, 115, 205, 295)
grid_y = (45, 95, 145, 195)

fourcc = cv2.VideoWriter_fourcc(*"XVID")
out = cv2.VideoWriter('output.avi', fourcc, 15.0, (320,240))

while(True):
    res_100 = "???"
    res_200 = "???"
    res_300 = "???"
    text ="???"

    # Capture frame-by-frame
    ret, frame = cap.read()
    
    img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    for temp_num in [100, 200, 300]:
        temp = cv2.imread("temp" + str(temp_num) + ".png", 0)
        result = cv2.matchTemplate(img, temp, cv2.TM_CCOEFF_NORMED)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)

        if max_val > 0.8:
            b = 0
            g = 0
            r = 0
        
            if temp_num == 100:
                b = 255
            if temp_num == 200:
                g = 255
            if temp_num == 300:
                r = 255

            top_left = max_loc
            w, h = temp.shape[::-1]
            bottom_right = (top_left[0] + w, top_left[1] + h)

            res_x = []
            res_y = []

            for i in [0, 1, 2]:
                if top_left[0] >= grid_x[i] and top_left[0] < grid_x[i + 1]:
                    if (i + 1 in res_x) == False:
                        res_x.append(i + 1)
                    for n in [0, 1, 2]:
                        if top_left[1] >= grid_y[n] and top_left[1] < grid_y[n + 1]:
                            if (n + 1 in res_y) == False:
                                res_y.append(n + 1)

                                #print("temp" + str(temp_num) + ".png = " + str(res_x[0]) + "-" + str(res_y[0]))

                                if temp_num == 100:
                                    res_100 = str(res_x[0]) + "-" + str(res_y[0])
                                if temp_num == 200:
                                    res_200 = str(res_x[0]) + "-" + str(res_y[0])
                                if temp_num == 300:
                                    res_300 = str(res_x[0]) + "-" + str(res_y[0])

                                text = str(res_x[0]) + "-" + str(res_y[0]) + "(" + str("{:.3}".format(max_val)) + ")"

            cv2.rectangle(frame, top_left, bottom_right, (b, g, r), 2)
            cv2.putText(frame, text, (top_left[0] - 5, top_left[1] - 5), cv2.FONT_HERSHEY_PLAIN, 0.8, (b, g, r), 1, cv2.LINE_AA)

    # Display the resulting frame
    # write the frame
    out.write(frame)

    cv2.imshow("frame", frame)

    key = cv2.waitKey(1)&0xff
    if key == ord("s"):

        label = tkinter.Label(None, text = "1 = " + res_100 + "\n2 = " + res_200 + "\n3 = " + res_300, font=("Times", "28"))
        label.pack()
        label.mainloop()

        cv2.imwrite("capture.png", frame)
        #break

    if key == ord("q"):
        break

# When everything done, release the capture
cap.release()
out.release()
cv2.destroyAllWindows()


上のコードでは、"s"キーが押された時に"tkinter"を使って検出対象の位置情報を表示させているが、
これは一例なので、検出結果から「ここで何かする」って意味になる。
更に別スレッド、別プロセスにすれば動画(画像)の取得を止めること無く「何かする」
が実行出きるので、実際の運用はそう言った使い方になる筈。

2018年1月4日木曜日

OpenCVのテンプレートマッチングを試す

以前にOpenCVを使って顔検出をやってみたが、今回はテンプレートマッチングで、
簡易的に数字を検出してみる。
  
下のページを参考にさせてもらいました。有り難うございました。
http://www.tech-tech.xyz/archives/3065942.html

本当は画像の中から文字を検出したかったのだが、意外と面倒そうだった。
手書きの文字やフォント不明の文字を認識したいわけではなく、予め用意した数字と
同じものさえ検出できればよかったので、テンプレート画像との一致を見つけることで
良しとした。

先ず、テンプレート画像を用意する。

上の画像から、検出したい数字の部分を切り取ってテンプレート画像を作る。
これら「1」「2」「3」のテンプレートを使って検出を行う。
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import cv2
import shutil

shutil.copyfile("test.jpg","result.jpg")

img = cv2.imread("result.jpg", 0)

for temp_num in [1, 2, 3]:
    temp = cv2.imread("temp" + str(temp_num) + ".png", 0)

    result = cv2.matchTemplate(img, temp, cv2.TM_CCOEFF_NORMED)

    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)

    if max_val > 0.8:
        top_left = max_loc
        w, h = temp.shape[::-1]
        bottom_right = (top_left[0] + w, top_left[1] + h)

        result = cv2.imread("result.jpg")
        cv2.rectangle(result,top_left, bottom_right, (255, 0, 0), 2)
        cv2.imwrite("result.jpg", result)

※追記1(2018/01/04 20:20)※
  誤検出を減らすように、テンプレートマッチングの結果から
"max_val"(グレースケールで最も高い輝度の値)が0.8より大きい時だけ 
枠表示をするように変更しました。
何回か試したところ、正常に検出できた場合の"max_val"は、ほぼ0.9以上。
誤検出の場合は、0.7以下でした。
そこで「エイヤッ」と、0.8を設定しました。


今回は検出する画像がjpg、テンプレート画像がpngという変則コードになってしまったが
実行できれば問題ない(本当かよ?)

実際のカードを作って、それらを並べ替えてやってみた。
元画像を印刷した後、切り取って数字カードを作る。

それらのカードを適当に並べ替えて検出してみた。

更に、枠を外してやってみた。

<結果>
・影があったり、余分な物が写っている画像でも、正常に検出ができた。

<問題点>
・検出する画像の数字部分とテンプレート画像のサイズが(大体)合っていないと、
以下のようになる。
間違った検出。画像の数字に対してテンプレートが小さい
 ・検出する画像が大きいと時間が掛かる。