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

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

新規登録して質問してみよう
ただいま回答率
85.48%
Keras

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

Q&A

解決済

2回答

389閲覧

KerasでSegnetを行いたい

uriuri

総合スコア47

Keras

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

0グッド

0クリップ

投稿2018/06/20 07:47

https://teratail.com/questions/131885#reply-200116
以前質問させていただいた部分は解決したのですが別の部分でエラーがでてしまいました。

イメージ説明

エラーを調べたところ画像を読み込めていないということです。
https://teratail.com/questions/97976

コードの参考はこちらです。
https://qiita.com/uni-3/items/a62daa5a03a02f5fa46d

画像の位置は
イメージ説明
dataset.pyの一部分
DataPath = '/home/ooo/××/SegNet/CamVid/'
変更しました。
プログラムは/home/ooo/××/segnet/
にdataset.pyとmodel.pyとtrain.pyが入っています。

いろいろディレクトリ指定などを変えたのですがダメでした。
ご教授いただけると幸いです。

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

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

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

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

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

guest

回答2

0

ベストアンサー

もう自分で直したほうが早いなと思って作成しました。

# segnet以下にtrain.py, model.py, dataset.pyが格納されています。 ─segnet ├─.idea ├─CamVid │ ├─test │ ├─testannot │ ├─train │ ├─trainannot │ ├─val │ └─valannot ├─docker │ ├─cpu │ └─gpu ├─Example_Models ├─Models ├─Scripts └─__pycache__

python

1# train.py 2import os 3import glob 4import numpy as np 5import keras 6 7from model import SegNet 8 9import dataset 10 11input_shape = (360, 480, 3) 12classes = 12 13epochs = 100 14batch_size = 1 15log_filepath='./logs/' 16 17data_shape = 360*480 18 19class_weighting = [0.2595, 0.1826, 4.5640, 0.1417, 0.5051, 0.3826, 9.6446, 1.8418, 6.6823, 6.2478, 3.0, 7.3614] 20 21## set gpu usage 22import tensorflow as tf 23config = tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=True, per_process_gpu_memory_fraction = 0.8)) 24session = tf.Session(config=config) 25keras.backend.tensorflow_backend.set_session(session) 26 27 28def main(): 29 print("loading data...") 30 ds = dataset.Dataset(classes=classes, 31 train_file="CamVid/train.txt", 32 test_file="CamVid/test.txt") 33 train_X, train_y = ds.load_data(root_path="CamVid", 34 mode='train') # need to implement, y shape is (None, 360, 480, classes) 35 36 train_X = ds.preprocess_inputs(train_X) 37 train_Y = ds.reshape_labels(train_y) 38 print("input data shape...", train_X.shape) 39 print("input label shape...", train_Y.shape) 40 41 test_X, test_y = ds.load_data(root_path="CamVid", 42 mode='test') # need to implement, y shape is (None, 360, 480, classes) 43 test_X = ds.preprocess_inputs(test_X) 44 test_Y = ds.reshape_labels(test_y) 45 46 tb_cb = keras.callbacks.TensorBoard(log_dir=log_filepath, histogram_freq=1, write_graph=True, write_images=True) 47 print("creating model...") 48 model = SegNet(input_shape=input_shape, classes=classes) 49 model.compile(loss="categorical_crossentropy", optimizer='adadelta', metrics=["accuracy"]) 50 51 model.fit(train_X, train_Y, batch_size=batch_size, epochs=epochs, 52 verbose=1, class_weight=class_weighting , validation_data=(test_X, test_Y), shuffle=True 53 , callbacks=[tb_cb]) 54 55 model.save('seg.h5') 56 57if __name__ == '__main__': 58 main()

python

1# dataset.py 2import cv2 3import numpy as np 4from pathlib import Path 5from keras.applications import imagenet_utils 6 7 8class Dataset: 9 def __init__(self, classes=12, train_file='train.txt', test_file='test.txt'): 10 self.train_file = train_file 11 self.test_file = test_file 12 self.data_shape = 360*480 13 self.classes = classes 14 15 def normalized(self, rgb): 16 #return rgb/255.0 17 norm=np.zeros((rgb.shape[0], rgb.shape[1], 3),np.float32) 18 19 b=rgb[:,:,0] 20 g=rgb[:,:,1] 21 r=rgb[:,:,2] 22 23 norm[:,:,0]=cv2.equalizeHist(b) 24 norm[:,:,1]=cv2.equalizeHist(g) 25 norm[:,:,2]=cv2.equalizeHist(r) 26 27 return norm 28 29 def one_hot_it(self, labels): 30 x = np.zeros([360,480,12]) 31 for i in range(360): 32 for j in range(480): 33 x[i,j,labels[i][j]] = 1 34 return x 35 36 def load_data(self, root_path, mode='train'): 37 data = [] 38 label = [] 39 root_path = Path(root_path) 40 if (mode == 'train'): 41 filename = self.train_file 42 else: 43 filename = self.test_file 44 45 with open(filename) as f: 46 txt = f.readlines() 47 for line in txt: 48 train_path, label_path = line.split(' ') 49 train_path = root_path.joinpath(train_path[15:]) 50 label_path = root_path.joinpath(label_path[15:].strip()) 51 data.append(self.normalized(cv2.imread(str(train_path)))) 52 label.append(self.one_hot_it(cv2.imread(str(label_path)))[:,:,0]) 53 print('.', end='') 54 #print("train data file", os.getcwd() + txt[i][0][7:]) 55 #print("label data raw", cv2.imread(os.getcwd() + '/CamVid/trainannot/0001TP_006690.png')) 56 return np.array(data), np.array(label) 57 58 59 def preprocess_inputs(self, X): 60 ### @ https://github.com/fchollet/keras/blob/master/keras/applications/imagenet_utils.py 61 """Preprocesses a tensor encoding a batch of images. 62 # Arguments 63 x: input Numpy tensor, 4D. 64 data_format: data format of the image tensor. 65 mode: One of "caffe", "tf". 66 - caffe: will convert the images from RGB to BGR, 67 then will zero-center each color channel with 68 respect to the ImageNet dataset, 69 without scaling. 70 - tf: will scale pixels between -1 and 1, 71 sample-wise. 72 # Returns 73 Preprocessed tensor. 74 """ 75 return imagenet_utils.preprocess_input(X) 76 77 def reshape_labels(self, y): 78 return np.reshape(y, (len(y), self.data_shape, self.classes))

投稿2018/06/25 11:07

編集2018/06/25 11:14
wakame

総合スコア1170

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

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

wakame

2018/06/25 11:09

ファイルパスをスライスしないといけないつらみ、そして改行コードを除去しないといけないつらみ。
uriuri

2018/06/25 11:31

わざわざありがとうございます。 実際に行ってみた結果、 loading data... Traceback (most recent call last): File "train.py", line 58, in <module> main() File "train.py", line 34, in main mode='train') # need to implement, y shape is (None, 360, 480, classes) File "/home/ooo/×××/SegNet/dataset.py", line 52, in load_data label.append(self.one_hot_it(cv2.imread(str(label_path)))[:,:,0]) File "/home/ooo/×××/SegNet/dataset.py", line 33, in one_hot_it x[i,j,labels[i][j]] = 1 TypeError: 'NoneType' object is not subscriptable txtの中身の問題でしょうか?
wakame

2018/06/25 11:34 編集

もちろん同じディレクトリ構成にされたのですよね?
uriuri

2018/06/25 11:44

txtの中身は /home/ooo/×××/SegNet/CamVid/train/0001TP_006690.png . . . です。
uriuri

2018/06/25 11:47

─SegNet ├─.idea ├─CamVid │ ├─test │ ├─testannot │ ├─train │ ├─trainannot │ ├─val │ └─valannot ├─docker │ ├─cpu │ └─gpu ├─Example_Models ├─Models ├─Scripts └─__pycache__ └─ train.py └─ model.py └─ dataset.py となっています。
uriuri

2018/06/25 12:14

txtが最初の状態 /SegNet/CamVid/train/0001TP_006690.png でも先ほどのエラーが起こってしまい変更し試した後の状態となっています。 /home/ooo/×××/SegNet/CamVid/train/0001TP_006690.png
wakame

2018/06/25 12:18

質問は上記に挙げたリンクとtrain.txtが同じか同じでないかなんですが・・・これは同じではないと解釈していいですか。そうすると私が作成したコードは動きません、質問者さんが改変した内容を期待していないからです。
uriuri

2018/06/26 01:04

ごめんなさい。 こちらのミスでtxtファイルを初期では2段構成だったものを1段に変えていたものが原因でした。 初期のpathで通りました。 /SegNet/CamVid/train/0001TP_006690.png loading dataを始めたのですが、 loading data... ...............................................................................................................................................................................................................................................................................................................................................................................Traceback (most recent call last): File "train.py", line 58, in <module> main() File "train.py", line 37, in main train_Y = ds.reshape_labels(train_y) File "/home/ooo/×××/SegNet/dataset.py", line 78, in reshape_labels return np.reshape(y, (len(y), self.data_shape, self.classes)) File "/home/ooo/anaconda3/lib/python3.6/site-packages/numpy/core/fromnumeric.py", line 257, in reshape return _wrapfunc(a, 'reshape', newshape, order=order) File "/home/ooo/anaconda3/lib/python3.6/site-packages/numpy/core/fromnumeric.py", line 52, in _wrapfunc return getattr(obj, method)(*args, **kwds) ValueError: cannot reshape array of size 63417600 into shape (367,172800,12) エラーの内容として367*172800=63417600 reshapeしようとする画像データのピクセル数が不足している訳ではなく同じ値なのですがエラーを吐いてしまいます。 参考サイトとして https://teratail.com/questions/97039 解決策を教えていただけると幸いです。 たびたびすみません。
wakame

2018/06/26 04:13

今試してみて自分も再現しました。この質問自体は解決したと思うので解決済にしてもらって、新たに出た質問は新規質問として投稿してもらえますか。
uriuri

2018/06/26 10:19

回答ありがとうございました。 とても助かりました。
guest

0

os.getcwd()はcurrent working directoryを返します。
プログラム自体はsegnet内で実行しているので、
/home/ooo/××/segnet/CamVid/train/0001TP_006690.pngを開こうとしていることでしょう。

正しく指定するなら、

python

1>>> DataPath = "/home/ooo/××/SegNet/CamVid/" 2>>> s = "/SegNet/CamVid/train/0001TP_006690.png" 3>>> DataPath + s[15:] 4'/home/ooo/××/SegNet/CamVid/train/0001TP_006690.png'

こんな感じだと思うので、cv2.imreadの中身を

python

1DataPath + txt[i][0][15:]

とかに変えて行けませんか。

投稿2018/06/20 18:36

hayataka2049

総合スコア30933

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

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

uriuri

2018/06/21 03:07

cv2.imreadの中身を変えて実行しましたが同じエラーが発生してしまいました
hayataka2049

2018/06/21 06:40

申し訳ないですがprintかなにか入れてパスが合ってるかどうか確認してください
uriuri

2018/06/24 01:49

すみません, どの部分をprintで確認すればよいのでしょうか. まだ未熟でごめんなさい.
hayataka2049

2018/06/24 02:12 編集

imreadの中身と同じものを表示してみて確認してください
uriuri

2018/06/25 04:37

print(DataPath + txt[i][0][15:]) を行った際、 Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'txt' is not defined となり print(DataPath)をした際は /home/ooo/××/SegNet/CamVid/ でした。 これはtxtがプログラム上で定義されていないからなのでしょうか。
uriuri

2018/06/25 04:40

/home/ooo/××/SegNet/CamVid/ に実行プログラムをいれました。 確認はターミナルでpythonの対話型にし import os をし printで確認しました。
hayataka2049

2018/06/25 08:58

train.pyの中にprintを埋め込んでください data.append(self.normalized(cv2.imread(DataPath + txt[i][0][15:]))) の行のすぐ上に print(DataPath + txt[i][0][15:]) と入れるということです
uriuri

2018/06/25 10:21

複雑だったのでpyファイルをsegnetからSegNetに移して実行しました。 コードは参考サイトどおりにしました。 print("train data file", os.getcwd() + txt[i][0][7:]) を行った結果は train data file /home/ooo/×××/SegNet/CamVid/train/0001TP_006690.png でありpathが通っていることは確認できました。 print("label data raw", cv2.imread(os.getcwd() + txt[i][1][7:][:-1])[:,:,0])) を行った結果 Traceback (most recent call last): File "train.py", line 4, in <module> import dataset File "/home/ooo/×××/SegNet/dataset.py", line 54 print("label data raw", cv2.imread(os.getcwd() + txt[i][1][7:][:-1])[:,:,0])) ^ SyntaxError: invalid syntax というエラーがでてしまいました。
hayataka2049

2018/06/25 10:24

ごめんなさい、上のコメントのコードが間違っていました。 print("label data raw", os.getcwd() + txt[i][1][7:]) でやってください。
uriuri

2018/06/25 10:25

print("label data raw", cv2.imread(os.getcwd() + txt[i][1][7:][:-1])[:,:,0]))をコメントアウトし train.pyを実行すると loading data... train data file /home/ooo/×××/SegNet/CamVid/train/0001TP_006690.png Traceback (most recent call last): File "train.py", line 54, in <module> main() File "train.py", line 31, in main train_X, train_y = ds.load_data('train') # need to implement, y shape is (None, 360, 480, classes) File "/home/iclab/ooo/×××/dataset.py", line 55, in load_data label.append(self.one_hot_it(cv2.imread(os.getcwd() + txt[i][1][7:][:-1])[:,:,0])) TypeError: 'NoneType' object is not subscriptable となってしまい label.append(self.one_hot_it(cv2.imread(os.getcwd() + txt[i][1][7:][:-1])[:,:,0] のところに問題があるのでしょうか。
uriuri

2018/06/25 10:29 編集

いま確認したところ label data raw /home/ooo/×××/SegNet になっておりpathが通っていないことが分かりました。
hayataka2049

2018/06/25 10:30

print("label data raw", os.getcwd() + txt[i][1][7:], txt[i][1])にするとどうなりますか?
uriuri

2018/06/25 10:32

train data fileと同じような形ですがpathの指定が違うのはなぜでしょうか。 どのようにpathを通すようにするかを教えていただけたら幸いです。
uriuri

2018/06/25 10:34

print("label data raw", os.getcwd() + txt[i][1][7:], txt[i][1]) を試したところ pathの位置は先ほどと同じ結果になりました。
hayataka2049

2018/06/25 10:36

txt[i][1]に該当する出力(スペースで区切られているのでわかります)はどうなりました?
uriuri

2018/06/25 10:39

print("label data raw", os.getcwd() + txt[i][1][7:], txt[i][1]) を行った結果出力として label data raw /home/ooo/×××/SegNet が表示されました。
hayataka2049

2018/06/25 10:43

print("label data raw", os.getcwd() + txt[i][0][7:], txt[i][0]) だとどうなりますか? こっちかも
hayataka2049

2018/06/25 10:44

パスは文字列加工で作っているだけです。なので、目的のパスになるように加工してやるしかありません
uriuri

2018/06/25 10:45

label data raw /home/ooo/×××/SegNet /SegNet/CamVid/train/0001TP_006690.png と表示されました。
hayataka2049

2018/06/25 10:50

今のファイル配置だと、画像の正しい絶対パスはどこになりますか? SegNet以下の構成が元と同じなら、SegNetまでのパスを結合してやればとりあえず動くとおもうので、それが一番楽だと思いました
uriuri

2018/06/25 11:04

画像の位置は /home/ooo/×××/SegNet /SegNet/CamVid/train/0001TP_006690.png となっています。 train.txtでは /SegNet/CamVid/train/0001TP_006690.png . . . となっています。 label data raw /home/ooo/×××/SegNet /SegNet/CamVid/train/0001TP_006690.png SegNetが重複していたのでtrain.txtを /CamVid/train/0001TP_006690.png にし行った際 data.append(self.normalized(cv2.imread(os.getcwd() + txt[i][0][7:]))) のprintが表示されませんでした。 SegNetの重複をなくしたい場合 print("label data raw", os.getcwd() + txt[i][0][7:], txt[i][0]) をどう変えたらいいでしょうか。
uriuri

2018/06/25 11:05

その後pathが通った際は label.append(self.one_hot_it(cv2.imread(os.getcwd() + txt[i][1][7:][:-1])[:,:,0])) の部分をprintでpathが通った形と同じようにすればいいのでしょうか。
wakame

2018/06/25 11:08

hayataka2049さんの負担が大きいなぁと思いましたので別回答用意しました。
hayataka2049

2018/06/25 11:09

なんかすみません。wakameさんにも質問者さんにも。
wakame

2018/06/25 11:12

こちらこそ横槍すみません。横目で見ていて思ったのは質問者さんの画像を保存しているディレクトリとソースコードを保存しているディレクトリが異なっていて、かつos.getcwd()でカレントディレクトリを取得しているもので余計にややこしくなってるなぁとということです。
uriuri

2018/06/25 11:32

知識不足でいろいろな方に迷惑をかけてしまい申し訳ありません。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問