質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Q&A

解決済

1回答

1270閲覧

tensorflowで画像の水増しがしたい

TyoNgc

総合スコア14

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

0グッド

0クリップ

投稿2017/11/26 07:04

編集2017/11/28 07:11

tensorflowで画像の水増しがしたい

現在tensorflowで画像認識を行っていますが、訓練画像、テスト画像の枚数を増やすためにtensorflowのコードを使い画像の水増しを行いたいと思っています。(コントラストを調節したり、画像回転させたりして)ですが具体的にどのようにコードに組み込めばよいか分かりません。

python

1# -*- coding: utf-8 -*- 2import sys 3import cv2 4import numpy as np 5import tensorflow as tf 6import tensorflow.python.platform 7import os 8 9NUM_CLASSES = 3 10IMAGE_SIZE = 28 11IMAGE_PIXELS = IMAGE_SIZE*IMAGE_SIZE*3 12 13#Flagはデフォルト値やヘルプ画面の説明文を定数のように登録できるTensorflow組み込み関数 14flags = tf.app.flags 15FLAGS = flags.FLAGS 16flags.DEFINE_string('train', 'train.txt', 'File name of train data') 17flags.DEFINE_string('test', 'test.txt', 'File name of train data') 18flags.DEFINE_string('image_dir', 'data', 'Directory of images') 19flags.DEFINE_string('train_dir', 'logs', 'Directory to put the training data.') 20#学習訓練の試行回数 21flags.DEFINE_integer('max_steps', 100, 'Number of steps to run trainer.') 22#一回の学習で何枚の画像を使うか 23flags.DEFINE_integer('batch_size', 10, 'Batch size' 24 'Must divide evenly into the dataset sizes.') 25#学習率、小さすぎると学習が進まない、大きすぎると誤差が収束しないまたは発散 26flags.DEFINE_float('learning_rate', 1e-5, 'Initial learning rate.') 27 28def inference(images_placeholder, keep_prob): 29""" 予測モデルを作成する関数 30 引数: 31 images_placeholder: 画像のplaceholder 32 keep_prob: dropout率のplace_holder 33 返り値: 34 y_conv: 各クラスの確率(のようなもの) 35 """ 36 # 重みを標準偏差0.1の正規分布で初期化 37 def weight_variable(shape): 38 initial = tf.truncated_normal(shape, stddev=0.1) 39 return tf.Variable(initial) 40 # バイアスを標準偏差0.1の正規分布で初期化 41 def bias_variable(shape): 42 initial = tf.constant(0.1, shape=shape) 43 return tf.Variable(initial) 44 # 畳み込み層の作成 45 def conv2d(x, W): 46 return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') 47 # プーリング層の作成 48 def max_pool_2x2(x): 49 return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], 50 strides=[1, 2, 2, 1], padding='SAME') 51 52 # 入力を28x28x3に変形,今回はカラー画像なので3(モノクロだと1) 53 x_image = tf.reshape(images_placeholder, [-1, 28, 28, 3]) 54 # 畳み込み層1の作成 55 with tf.name_scope('conv1') as scope: 56 W_conv1 = weight_variable([5, 5, 3, 32]) 57 b_conv1 = bias_variable([32]) 58 h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) 59 tf.summary.histogram("wc1", W_conv1) 60 with tf.name_scope('pool1') as scope: 61 h_pool1 = max_pool_2x2(h_conv1) 62 63 # 畳み込み層2の作成 64 with tf.name_scope('conv2') as scope: 65 # 第一レイヤーでの出力を第2レイヤー入力にしてもう一度フィルタリング実施 66 # 5px*5pxの範囲で画像(?)をフィルターしている 67 # inputが32なのは第一レイヤーの32個の特徴の出力を入力するから 68 # 64個の特徴を検出する 69 W_conv2 = weight_variable([5, 5, 32, 64]) 70 b_conv2 = bias_variable([64]) 71 # 検出した特徴の整理(第一レイヤーと同じ) 72 h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) 73 tf.summary.histogram("wc2", W_conv2) 74 # プーリング層2の作成 75 with tf.name_scope('pool2') as scope: 76 h_pool2 = max_pool_2x2(h_conv2) 77 # 全結合層1の作成 78 with tf.name_scope('fc1') as scope: 79 W_fc1 = weight_variable([7*7*64, 1024]) 80 b_fc1 = bias_variable([1024]) 81 #画像の解析結果をベクトルへ変換 82 h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) 83 # 第一、第二と同じく、検出した特徴を活性化させている 84 h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) 85 # dropoutの設定 86 h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) 87 # 全結合層2の作成 88 with tf.name_scope('fc2') as scope: 89 W_fc2 = weight_variable([1024, NUM_CLASSES]) 90 b_fc2 = bias_variable([NUM_CLASSES]) 91 # ソフトマックス関数による正規化 92 with tf.name_scope('softmax') as scope: 93 y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) 94 # 各ラベルの確率のようなものを返す 95 return y_conv 96 97def loss(logits, labels): 98 """ lossを計算する関数 99 引数: 100 logits: ロジットのtensor, float - [batch_size, NUM_CLASSES] 101 labels: ラベルのtensor, int32 - [batch_size, NUM_CLASSES] 102 返り値: 103 cross_entropy: 交差エントロピーのtensor, float 104 """ 105 # 交差エントロピーの計算 106 cross_entropy = -tf.reduce_sum(labels*tf.log(logits)) 107 #cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits)) 108 # TensorBoardで表示するよう指定 109 tf.summary.scalar("cross_entropy", cross_entropy) 110 return cross_entropy 111 112def training(loss, learning_rate): 113 """ 訓練のOpを定義する関数 114 引数: 115 loss: 損失のtensor, loss()の結果 116 learning_rate: 学習係数 117 返り値: 118 train_step: 訓練のOp 119 """ 120 train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss) 121 return train_step 122 123def accuracy(logits, labels): 124 """ 正解率(accuracy)を計算する関数 125 引数: 126 logits: inference()の結果 127 labels: ラベルのtensor, int32 - [batch_size, NUM_CLASSES] 128 返り値: 129 accuracy: 正解率(float) 130 """ 131 # 予測ラベルと正解ラベルが等しいか比べる。同じ値であればTrueが返される 132 # argmaxは配列の中で一番値の大きい箇所のindex(=一番正解だと思われるラベルの番号)を返す 133 correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1)) 134 accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) 135 tf.summary.scalar("accuracy", accuracy) 136 return accuracy 137if __name__ == '__main__': 138 f = open(FLAGS.train, 'r') 139 # データを入れる配列 140 train_image = [] 141 train_label = [] 142 for line in f: 143 # 改行を除いてスペース区切りにする 144 line = line.rstrip() 145 l = line.split() 146 # データを読み込んで28x28に縮小 147 img = cv2.imread(FLAGS.image_dir + '/' + l[0]) 148 img = cv2.resize(img, (28, 28)) 149 # 一列にした後、0-1のfloat値にする 150 train_image.append(img.flatten().astype(np.float32)/255.0) 151 # ラベルを1-of-k方式で用意する 152 tmp = np.zeros(NUM_CLASSES) 153 tmp[int(l[1])] = 1 154 train_label.append(tmp) 155 # numpy形式に変換 156 train_image = np.asarray(train_image) 157 train_label = np.asarray(train_label) 158 f.close() 159 f = open(FLAGS.test, 'r') 160 test_image = [] 161 test_label = [] 162 for line in f: 163 line = line.rstrip() 164 l = line.split() 165 img = cv2.imread(FLAGS.image_dir + '/' + l[0]) 166 img = cv2.resize(img, (28, 28)) 167 test_image.append(img.flatten().astype(np.float32)/255.0) 168 tmp = np.zeros(NUM_CLASSES) 169 tmp[int(l[1])] = 1 170 test_label.append(tmp) 171 test_image = np.asarray(test_image) 172 test_label = np.asarray(test_label) 173 f.close() 174 175 #TensorBoardのグラフに出力するスコープを指定 176 with tf.Graph().as_default(): 177 # 画像を入れる仮のTensor(28*28*3(IMAGE_PIXELS)次元の画像が任意の枚数(None)分はいる) 178 images_placeholder = tf.placeholder("float", shape=(None, IMAGE_PIXELS)) 179 # ラベルを入れる仮のTensor(3(NUM_CLASSES)次元のラベルが任意の枚数(None)分入る) 180 labels_placeholder = tf.placeholder("float", shape=(None, NUM_CLASSES)) 181 # dropout率を入れる仮のTensor 182 keep_prob = tf.placeholder("float") 183 # inference()を呼び出してモデルを作る 184 logits = inference(images_placeholder, keep_prob) 185 # loss()を呼び出して損失を計算 186 loss_value = loss(logits, labels_placeholder) 187 # training()を呼び出して訓練 188 train_op = training(loss_value, FLAGS.learning_rate) 189 # 精度の計算 190 acc = accuracy(logits, labels_placeholder) 191 # 保存の準備 192 saver = tf.train.Saver() 193 # Sessionの作成 194 sess = tf.Session() 195 # 変数の初期化 196 sess.run(tf.global_variables_initializer()) 197 # TensorBoardで表示する値の設定 198 summary_op = tf.summary.merge_all() 199 summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph) 200 # 訓練の実行 201 for step in range(FLAGS.max_steps): 202 for i in range(int(len(train_image)/FLAGS.batch_size)): 203 # batch_size分の画像に対して訓練の実行 204 batch = FLAGS.batch_size*i 205 # feed_dictでplaceholderに入れるデータを指定する 206 sess.run(train_op, feed_dict={ 207 images_placeholder: train_image[batch:batch+FLAGS.batch_size], 208 labels_placeholder: train_label[batch:batch+FLAGS.batch_size], 209 keep_prob: 0.5}) 210 # 1 step終わるたびに精度を計算する 211 train_accuracy = sess.run(acc, feed_dict={ 212 images_placeholder: train_image, 213 labels_placeholder: train_label, 214 keep_prob: 1.0}) 215 print("step %d, training accuracy %g"%(step, train_accuracy)) 216 # 1 step終わるたびにTensorBoardに表示する値を追加する 217 summary_str = sess.run(summary_op, feed_dict={ 218 images_placeholder: train_image, 219 labels_placeholder: train_label, 220 keep_prob: 1.0}) 221 summary_writer.add_summary(summary_str, step) 222 # 訓練が終了したらテストデータに対する精度を表示 223 print("test accuracy %g"%sess.run(acc, feed_dict={ 224 images_placeholder: test_image, 225 labels_placeholder: test_label, 226 keep_prob: 1.0})) 227 # 最終的なモデルを保存 228 save_path = saver.save(sess, os.getcwd() + "\model.ckpt")

tf.image.random_brightness
tf.image.random_contrast
tf.image.random_flip_left_right
このようなコードを使って画像の枚数を増やして認識率を上げていきたいです。
初心者ですので何もわからない状態ですがご教授を頂ければ嬉しいです。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

そこまでわかっていれば答えはすぐそこではないでしょうか?
Hironsanさんの投稿@qiitaが参考になりそうです。実際のコードはcifar10でしょうか。

入れる場所は、テキストファイルから一行ずつ読みだしてファイルをリストに格納するところで、格納する前にあれこれ変えてから格納する感じです。

投稿2017/11/26 08:01

退会済みユーザー

退会済みユーザー

総合スコア0

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

TyoNgc

2017/11/28 07:15

コードを足すのは、test_image.append(img.flatten().astype(np.float32)/255.0)のコードの後で問題ないでしょうか。既存の画像がただ変更されているような気がするのですが(認識率もあまり変わりませんでした)、新たに変数を作り元画像に足すのでしょうか。的外れでしたら申し訳ありません。
退会済みユーザー

退会済みユーザー

2017/11/28 12:57

>コードを足すのは、 そうだと思います。 >既存の画像がただ変更されているような気がする 変更後の画像を用意して、それをリストに加える感じでしょうか。pythonを触っていると、「データを複製したら参照が複製されているだけで、実体は複製できなかった」ということがよくあります。それが起きているかもしれませんね。 >新たに変数を作り元画像に足すのでしょうか 参照の複製ではなく、実際にデータを複製して、リストに継ぎ足す感じです。実際に見えないと心配であれば、水増ししたデータを書き出して、それから束ねなおす方が安心ですね。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問