2018年1月15日月曜日

画像認識プログラム(Tensorflow, Keras使用)

#! /usr/bin/python3

import os
os.environ[ 'TF_CPP_MIN_LOG_LEVEL'] = '2'

import numpy as np
import matplotlib.pyplot as plt

import keras

from keras.utils import np_utils
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.preprocessing.image import array_to_img, img_to_array, list_pictures, load_img

from sklearn.model_selection import train_test_split

from PIL import Image

X = []
Y = []

# サンプル入力
for picture in list_pictures('./samle'):
 img = img_to_array(load_img(picture, grayscale=True, target_size=(200,200)))
 X.append(img)
 Y.append(0)


# 参考情報入力
for picture in list_pictures('./reference'):
 img = img_to_array(load_img(picture, grayscale=True, target_size=(200,200)))
 X.append(img)
 Y.append(1)

X = np.asarray(X)
Y = np.asarray(Y)
X = X.astype('float32')
X = X / 255.0

Y = np_utils.to_categorical(Y, 2)
indices = np.array(range(X.shape[0]))


# 学習用データとテストデータ
X_train, X_test, Y_train, Y_test, indices_train, indices_test = train_test_split(X, Y, indices, test_size=0.2, random_state=111)



print('X shape:', X.shape)
print('Y shape:', Y.shape)
print(X.shape[0], 'all samples')    # すべてのサンプル数
print('X_train shape:', X_train.shape)
print('X_test shape:', X_test.shape)
print('Y_train shape:', Y_train.shape)
print('Y_test shape:', Y_test.shape)
print(X_train.shape[0], 'train samples')    # 訓練サンプル数
print(X_test.shape[0], 'test samples')    # テストサンプル数

#----------------------------------------------------------------------------------------------------------------------------------

#plt.imshow(X[100])    # 入力画像の例を表示
#plt.imshow(X_test[100].reshape([40, 40]))    # 入力画像の例を表示
#plt.gray()

#print(X_train[100])
#print(X_test[100])
#print(Y_train[100])
#print(Y_test[100])

#---------------------------------------------------------------------------------------------------------------------------------
# CNNのモデルの作成

model = Sequential()

model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(200, 200, 1)))
model.add(Dropout(0.5))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(Dropout(0.5))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(32, activation='relu'))
model.add(Dense(2, activation='softmax'))

model.summary()        # モデル情報の表示

#-------------------------------------------------------------------------------------------------------------------------------------
batch_size = 128         # バッチサイズ
nb_epoch = 10           # 繰り返し回数

#--------------------------------------------------------------------------------------------------------------------------------------
# 学習パラメータの設定
model.compile(loss='categorical_crossentropy',
              optimizer='adam', metrics=['accuracy'])

# モデルの学習
history = model.fit(X_train, Y_train,
                    batch_size=batch_size, epochs=nb_epoch,
                    validation_data=(X_test, Y_test))

# 学習結果の評価
score = model.evaluate(X_test, Y_test, verbose=0)
print('Test score:', score[0])
print('Test accuracy:', score[1])