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

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

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

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

Q&A

解決済

1回答

1340閲覧

CNNをカラー画像ではできるのに、モノクロ画像でできません。

kenyy

総合スコア13

Python 3.x

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

0グッド

0クリップ

投稿2018/11/14 05:16

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(モノクロ画像)にするとエラーがでて、プログラムが動きません。

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

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

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

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

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

tiitoi

2018/11/14 05:32

train_image.shape を print するとなんてでますか。形状の不一致なので、これが (N, 625) になっていないからエラーになっているのだと思いますが。
kenyy

2018/11/14 05:45

返信ありがとうございます。(8192, 1875)とでます。
tiitoi

2018/11/14 06:06

それはおかしいですよね。train_image を作ってるとこに追加している cv2.resize(img, (IMAGE, IMAGE)) でちゃんと 25x25 にリサイズできていることを確認してみてください。
kenyy

2018/11/14 06:27

img.shapeをprintしたところ、(25,25,3)とでました。
kenyy

2018/11/14 06:29

できました。img = cv2.imread(l[0])をimg = cv2.imread(l[0],0)に変えたらできました!!ありがとうございました。
guest

回答1

0

ベストアンサー

img.shapeをprintしたところ、(25,25,3)とでました。

それが原因ですね。

cv2.imread() は元の画像がグレースケールでも、なにも指定しない場合はカラー画像に変換して読み込まれてしまいます。
グレースケール画像として読み込む場合は、

cv2.imread('画像のパス', cv2.IMREAD_GRAYSCALE) と第2引数を指定してあげてください。

投稿2018/11/14 06:30

tiitoi

総合スコア21956

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

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

kenyy

2018/11/14 06:33

ご丁寧にありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問