CNNをカラー画像ではできるのに、モノクロ画像でできません。
解決済
回答 1
投稿
- 評価
- クリップ 0
- VIEW 1,976
tensorflowのバージョンは1.1.0を使用しています。
複数のモノクロ画像を学習して予測モデルを作りたいのですが、以下のようなエラーがでており詰まっています。
発生している問題・エラーメッセージ
Traceback (most recent call last):
File "<stdin>", line 48, in <module>
File "C:\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py", line 778, in run
run_metadata_ptr)
File "C:\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\client\session.py", line 961, in _run
% (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape())))
ValueError: Cannot feed value of shape (256, 1875) for Tensor 'Placeholder:0', which has shape '(?, 625)'
該当のソースコード
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import cv2
import time
import random
import numpy as np
import tensorflow as tf
import tensorflow.python.platform
NUM_CLASSES = 2
IMAGE = 25
CHANNEL = 1
IMAGE_PIXELS = IMAGE*IMAGE*CHANNEL
zenketu = 7
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('train', './train.txt', 'File name of train data')
flags.DEFINE_string('test', './test.txt', 'File name of train data')
flags.DEFINE_string('train_dir', './Learnimage', 'Directory to put the training data.')
flags.DEFINE_integer('max_steps', 100, 'Number of steps to run trainer.')
flags.DEFINE_integer('batch_size',256, 'Batch size Must divide evenly into the dataset sizes.')
flags.DEFINE_float('learning_rate', 1e-5, 'Initial learning rate.')
sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True))
def inference(images_placeholder, keep_prob):
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, 1, 1, 1],strides=[1, 2, 2, 1], padding='SAME')
x_image = tf.reshape(images_placeholder, [-1, IMAGE, IMAGE, CHANNEL])
with tf.name_scope('conv1') as scope:
W_conv1 = weight_variable([5, 5, CHANNEL, IMAGE])
b_conv1 = bias_variable([IMAGE])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
with tf.name_scope('pool1') as scope:
h_pool1 = max_pool_2x2(h_conv1)
with tf.name_scope('conv2') as scope:
W_conv2 = weight_variable([5, 5, IMAGE, (IMAGE*2)])
b_conv2 = bias_variable([IMAGE*2])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
with tf.name_scope('pool2') as scope:
h_pool2 = max_pool_2x2(h_conv2)
with tf.name_scope('fc1') as scope:
W_fc1 = weight_variable([zenketu*zenketu*(IMAGE*2), 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, zenketu*zenketu*(IMAGE*2)])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
with tf.name_scope('fc2') as scope:
W_fc2 = weight_variable([1024, NUM_CLASSES])
b_fc2 = bias_variable([NUM_CLASSES])
with tf.name_scope('softmax') as scope:
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
return y_conv
def loss(logits, labels):
cross_entropy = -tf.reduce_sum(labels*tf.log(logits))
tf.summary.scalar("cross_entropy", cross_entropy)
return cross_entropy
def training(loss, learning_rate):
train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss)
return train_step
def accuracy(logits, labels):
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
tf.summary.scalar("accuracy", accuracy)
return accuracy
if __name__ == '__main__':
f = open(FLAGS.train, 'r')
train_image = []
train_label = []
for line in f:
line = line.rstrip()
l = line.split()
img = cv2.imread(l[0])
img = cv2.resize(img, (IMAGE, IMAGE))
train_image.append(img.flatten().astype(np.float32)/255.0)
tmp = np.zeros(NUM_CLASSES)
tmp[int(l[1])] = 1
train_label.append(tmp)
train_image = np.asarray(train_image)
train_label = np.asarray(train_label)
f.close()
f = open(FLAGS.test, 'r')
test_image = []
test_label = []
for line in f:
line = line.rstrip()
l = line.split()
img = cv2.imread(l[0])
img = cv2.resize(img, (IMAGE, IMAGE))
test_image.append(img.flatten().astype(np.float32)/255.0)
tmp = np.zeros(NUM_CLASSES)
tmp[int(l[1])] = 1
test_label.append(tmp)
test_image = np.asarray(test_image)
test_label = np.asarray(test_label)
f.close()
with tf.Graph().as_default():
images_placeholder = tf.placeholder("float", shape=(None,IMAGE_PIXELS))
labels_placeholder = tf.placeholder("float", shape=(None, NUM_CLASSES))
keep_prob = tf.placeholder("float")
logits = inference(images_placeholder, keep_prob)
loss_value = loss(logits, labels_placeholder)
train_op = training(loss_value, FLAGS.learning_rate)
acc = accuracy(logits, labels_placeholder)
saver = tf.train.Saver()
sess = tf.Session()
sess.run(tf.global_variables_initializer())
summary_op = tf.summary.merge_all()
summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph)
for step in range(FLAGS.max_steps):
for i in range(len(train_image)//FLAGS.batch_size):
batch = FLAGS.batch_size*i
sess.run(train_op, feed_dict={images_placeholder: train_image[batch:batch+FLAGS.batch_size],
labels_placeholder: train_label[batch:batch+FLAGS.batch_size],
keep_prob: 0.5})
train_accuracy = sess.run(acc,
feed_dict={images_placeholder: train_image,
labels_placeholder: train_label,
keep_prob: 1.0})
print( "step %d, training accuracy %g"%(step, train_accuracy))
summary_str = sess.run(summary_op,
feed_dict={images_placeholder: train_image,
labels_placeholder: train_label,
keep_prob: 1.0})
summary_writer.add_summary(summary_str, step)
print ("test accuracy %g"%sess.run(acc,
feed_dict={images_placeholder: test_image,
labels_placeholder: test_label,
keep_prob: 1.0}))
save_path = saver.save(sess,"./model.ckpt")
試したこと
CHANNEL = 3(カラー画像)の場合だと問題なくプログラムが動きます。
しかし、
この値を1(モノクロ画像)にするとエラーがでて、プログラムが動きません。
-
気になる質問をクリップする
クリップした質問は、後からいつでもマイページで確認できます。
またクリップした質問に回答があった際、通知やメールを受け取ることができます。
クリップを取り消します
-
良い質問の評価を上げる
以下のような質問は評価を上げましょう
- 質問内容が明確
- 自分も答えを知りたい
- 質問者以外のユーザにも役立つ
評価が高い質問は、TOPページの「注目」タブのフィードに表示されやすくなります。
質問の評価を上げたことを取り消します
-
評価を下げられる数の上限に達しました
評価を下げることができません
- 1日5回まで評価を下げられます
- 1日に1ユーザに対して2回まで評価を下げられます
質問の評価を下げる
teratailでは下記のような質問を「具体的に困っていることがない質問」、「サイトポリシーに違反する質問」と定義し、推奨していません。
- プログラミングに関係のない質問
- やってほしいことだけを記載した丸投げの質問
- 問題・課題が含まれていない質問
- 意図的に内容が抹消された質問
- 過去に投稿した質問と同じ内容の質問
- 広告と受け取られるような投稿
評価が下がると、TOPページの「アクティブ」「注目」タブのフィードに表示されにくくなります。
質問の評価を下げたことを取り消します
この機能は開放されていません
評価を下げる条件を満たしてません
質問の評価を下げる機能の利用条件
この機能を利用するためには、以下の事項を行う必要があります。
- 質問回答など一定の行動
-
メールアドレスの認証
メールアドレスの認証
-
質問評価に関するヘルプページの閲覧
質問評価に関するヘルプページの閲覧
checkベストアンサー
+2
img.shapeをprintしたところ、(25,25,3)とでました。
それが原因ですね。
cv2.imread()
は元の画像がグレースケールでも、なにも指定しない場合はカラー画像に変換して読み込まれてしまいます。
グレースケール画像として読み込む場合は、
cv2.imread('画像のパス', cv2.IMREAD_GRAYSCALE)
と第2引数を指定してあげてください。
投稿
-
回答の評価を上げる
以下のような回答は評価を上げましょう
- 正しい回答
- わかりやすい回答
- ためになる回答
評価が高い回答ほどページの上位に表示されます。
-
回答の評価を下げる
下記のような回答は推奨されていません。
- 間違っている回答
- 質問の回答になっていない投稿
- スパムや攻撃的な表現を用いた投稿
評価を下げる際はその理由を明確に伝え、適切な回答に修正してもらいましょう。
15分調べてもわからないことは、teratailで質問しよう!
- ただいまの回答率 88.23%
- 質問をまとめることで、思考を整理して素早く解決
- テンプレート機能で、簡単に質問をまとめられる
質問への追記・修正、ベストアンサー選択の依頼
tiitoi
2018/11/14 14:32
train_image.shape を print するとなんてでますか。形状の不一致なので、これが (N, 625) になっていないからエラーになっているのだと思いますが。
kenyy
2018/11/14 14:45
返信ありがとうございます。(8192, 1875)とでます。
tiitoi
2018/11/14 15:06
それはおかしいですよね。train_image を作ってるとこに追加している cv2.resize(img, (IMAGE, IMAGE)) でちゃんと 25x25 にリサイズできていることを確認してみてください。
kenyy
2018/11/14 15:27
img.shapeをprintしたところ、(25,25,3)とでました。
kenyy
2018/11/14 15:29
できました。img = cv2.imread(l[0])をimg = cv2.imread(l[0],0)に変えたらできました!!ありがとうございました。