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

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

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

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

802閲覧

flaskとOpenCVによる画像認識のエラー

masa.taka

総合スコア22

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

1クリップ

投稿2020/02/15 15:17

編集2020/02/16 00:38

前提・実現したいこと

flaskにて、OpenCVを活用した
簡単な画像認識アプリを作成してます。
(読み込んだ画像の分類)

読み込んだ画像の分類結果を返すresult.htmlに
遷移する段階にて、以下のようなエラーが発生してしまい、よく意味がわからず、
非常に困っております。

具体的な原因、解決策がお分かりの方、
ぜひご教示頂ければ幸いです。

発生している問題・エラーメッセージ

raise ValueError("Tensor %s is not an element of this graph." % obj)

pyファイル

import pickle import numpy as np from flask import Flask, render_template, request, redirect, url_for from keras.models import load_model import cv2 import numpy as np from keras.models import load_model import matplotlib.pyplot as plt import io from keras.preprocessing.image import img_to_array, load_img app = Flask(__name__) # 機械学習モデルの読込 model = load_model("./data/cnn_model.h5") model.load_weights("./data/cnn_weights.h5") @app.route("/") def index(): return render_template("index.html") @app.route("/result", methods=['POST']) def result(): if request.files["image"]: img_file = request.files["image"] f = img_file.stream.read() bin_data = io.BytesIO(f) file_bytes = np.asarray(bytearray(bin_data.read()), dtype=np.uint8) img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR) img = cv2.resize(img, (32, 32)) in_rows = 32 in_cols = 32 in_colors = 3 labels = [ 'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck' ] img = img.reshape(-1, in_rows, in_cols, in_colors).astype("float32") / 255 r = model.predict(img, batch_size=32, verbose=1) res = r[0] return render_template("result.html", res=res) else: return redirect(url_for('index'))

index.html

<!DOCTYPE html> <html> <head> <title>アプリ</title> <link rel="stylesheet" type="text/css" href="../static/css/style.css"> </head> <body class="main"> <div class="heading"> <h1>画像認識アプリ Image-Recognition</h1> </div> <div> <form method="post" action="/result" enctype="multipart/form-data"> <p> <input type="file" name="image" accept="image/png, image/jpeg" placeholder="Image Url"> </p> <p> <input type="submit" value="Go!"> </p> </form> </div> </body> </html>

result.html

<!DOCTYPE html> <html> <head> <title>Result</title>le.css <link rel="stylesheet" type="text/css" href="../static/css/style.css"> </head> <body class="main"> <div class="heading"> 予測結果は...<h1 align="center">{{labels[res.argmax()]}}</h1> </div> </body> </html>

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

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

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

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

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

guest

回答1

0

ベストアンサー

Flask and Keras model Error ''_thread._local' object has no attribute 'value''?に記載されているとおり、tensorflowのバージョンが原因だと思われます。

ざっと以下のような手順にて当方環境では動作することが確認できました。

  • 前準備としてkeras/examples/cifar10_cnn.pyを使ってGoogle colab上で学習済みデータ(.h5)を作成。

  • ついでに指定した画像を予測するだけのコードをGoogle colab上で正常に動作するか確認。

  • python=3.6.9, tensoflow=1.15.0, keras=2.2.5の環境を構築。Flaskなどその他は最新。

  • raise ValueError("Tensor %s is not an element of this graph." % objが出たので

django+keras+apache+mod_wsgiで<tensor> is not an element of this graphが出た話。を参考に修正。

  • result.htmllevelsを渡すようにする。

参考まで。

予測データ作成

Python

1''' 2#Train a simple deep CNN on the CIFAR10 small images dataset. 3It gets to 75% validation accuracy in 25 epochs, and 79% after 50 epochs. 4(it's still underfitting at that point, though). 5''' 6import keras 7from keras.datasets import cifar10 8from keras.preprocessing.image import ImageDataGenerator 9from keras.models import Sequential 10from keras.layers import Dense, Dropout, Activation, Flatten 11from keras.layers import Conv2D, MaxPooling2D 12import os 13 14batch_size = 32 15num_classes = 10 16epochs = 100 17data_augmentation = True 18num_predictions = 20 19#save_dir = os.path.join(os.getcwd(), 'saved_models') 20save_dir = "." 21model_name = 'cnn_model.h5' 22w_name = 'cnn_weights.h5' 23 24# The data, split between train and test sets: 25(x_train, y_train), (x_test, y_test) = cifar10.load_data() 26print('x_train shape:', x_train.shape) 27print(x_train.shape[0], 'train samples') 28print(x_test.shape[0], 'test samples') 29 30# Convert class vectors to binary class matrices. 31y_train = keras.utils.to_categorical(y_train, num_classes) 32y_test = keras.utils.to_categorical(y_test, num_classes) 33 34model = Sequential() 35model.add(Conv2D(32, (3, 3), padding='same', 36 input_shape=x_train.shape[1:])) 37model.add(Activation('relu')) 38model.add(Conv2D(32, (3, 3))) 39model.add(Activation('relu')) 40model.add(MaxPooling2D(pool_size=(2, 2))) 41model.add(Dropout(0.25)) 42 43model.add(Conv2D(64, (3, 3), padding='same')) 44model.add(Activation('relu')) 45model.add(Conv2D(64, (3, 3))) 46model.add(Activation('relu')) 47model.add(MaxPooling2D(pool_size=(2, 2))) 48model.add(Dropout(0.25)) 49 50model.add(Flatten()) 51model.add(Dense(512)) 52model.add(Activation('relu')) 53model.add(Dropout(0.5)) 54model.add(Dense(num_classes)) 55model.add(Activation('softmax')) 56 57# initiate RMSprop optimizer 58opt = keras.optimizers.RMSprop(lr=0.0001, decay=1e-6) 59 60# Let's train the model using RMSprop 61model.compile(loss='categorical_crossentropy', 62 optimizer=opt, 63 metrics=['accuracy']) 64 65x_train = x_train.astype('float32') 66x_test = x_test.astype('float32') 67x_train /= 255 68x_test /= 255 69 70if not data_augmentation: 71 print('Not using data augmentation.') 72 model.fit(x_train, y_train, 73 batch_size=batch_size, 74 epochs=epochs, 75 validation_data=(x_test, y_test), 76 shuffle=True) 77else: 78 print('Using real-time data augmentation.') 79 # This will do preprocessing and realtime data augmentation: 80 datagen = ImageDataGenerator( 81 featurewise_center=False, # set input mean to 0 over the dataset 82 samplewise_center=False, # set each sample mean to 0 83 featurewise_std_normalization=False, # divide inputs by std of the dataset 84 samplewise_std_normalization=False, # divide each input by its std 85 zca_whitening=False, # apply ZCA whitening 86 zca_epsilon=1e-06, # epsilon for ZCA whitening 87 rotation_range=0, # randomly rotate images in the range (degrees, 0 to 180) 88 # randomly shift images horizontally (fraction of total width) 89 width_shift_range=0.1, 90 # randomly shift images vertically (fraction of total height) 91 height_shift_range=0.1, 92 shear_range=0., # set range for random shear 93 zoom_range=0., # set range for random zoom 94 channel_shift_range=0., # set range for random channel shifts 95 # set mode for filling points outside the input boundaries 96 fill_mode='nearest', 97 cval=0., # value used for fill_mode = "constant" 98 horizontal_flip=True, # randomly flip images 99 vertical_flip=False, # randomly flip images 100 # set rescaling factor (applied before any other transformation) 101 rescale=None, 102 # set function that will be applied on each input 103 preprocessing_function=None, 104 # image data format, either "channels_first" or "channels_last" 105 data_format=None, 106 # fraction of images reserved for validation (strictly between 0 and 1) 107 validation_split=0.0) 108 109 # Compute quantities required for feature-wise normalization 110 # (std, mean, and principal components if ZCA whitening is applied). 111 datagen.fit(x_train) 112 113 # Fit the model on the batches generated by datagen.flow(). 114 model.fit_generator(datagen.flow(x_train, y_train, 115 batch_size=batch_size), 116 epochs=epochs, 117 validation_data=(x_test, y_test), 118 workers=4) 119 120# Save model and weights 121if not os.path.isdir(save_dir): 122 os.makedirs(save_dir) 123model_path = os.path.join(save_dir, model_name) 124model.save(model_path) 125print('Saved trained model at %s ' % model_path) 126 127w_path = os.path.join(save_dir, w_name) 128model.save_weights(w_path) 129 130# Score trained model. 131scores = model.evaluate(x_test, y_test, verbose=1) 132print('Test loss:', scores[0]) 133print('Test accuracy:', scores[1])

環境構築とテスト実行

>conda create -n cifar10 python=3.6.9 tensorflow=1.15.0 keras=2.2.5 matplotlib flask >conda activate cifar10 (VS2015ビルド環境がないと怒られるが無視) >conda install -c conda-forge opencv >python app.py (いろいろ警告が出るが無視)

app.py

Python

1import pickle 2import numpy as np 3from flask import Flask, render_template, request, redirect, url_for 4 5from keras.models import load_model 6import cv2 7import numpy as np 8import matplotlib.pyplot as plt 9import io 10import tensorflow as tf 11import sys 12 13app = Flask(__name__) 14 15# 機械学習モデルの読込 16model = load_model("./templates/cnn_model.h5") 17model.load_weights("./templates/cnn_weights.h5") 18 19graph = tf.get_default_graph() 20 21@app.route("/") 22def index(): 23 return render_template("index.html") 24 25@app.route("/result", methods=['POST']) 26def result(): 27 if request.files["image"]: 28 img_file = request.files["image"] 29 f = img_file.stream.read() 30 bin_data = io.BytesIO(f) 31 file_bytes = np.asarray(bytearray(bin_data.read()), dtype=np.uint8) 32 33 img = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR) 34 img = cv2.resize(img, (32, 32)) 35 36 in_rows = 32 37 in_cols = 32 38 in_colors = 3 39 40 labels = [ 41 'airplane', 42 'automobile', 43 'bird', 44 'cat', 45 'deer', 46 'dog', 47 'frog', 48 'horse', 49 'ship', 50 'truck' 51 ] 52 53 img = img.reshape(-1, in_rows, in_cols, 54 in_colors).astype("float32") / 255 55 56 with graph.as_default(): 57 r = model.predict(img, batch_size=32, verbose=1) 58 res = r[0] 59 print(res, file=sys.stdout) 60 return render_template("result.html", res=res, labels=labels) 61 else: 62 return redirect(url_for('index')) 63 64if __name__ == '__main__': 65 app.run(debug=True)

投稿2020/02/16 01:37

編集2020/02/16 02:03
can110

総合スコア38278

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

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

masa.taka

2020/02/16 02:23 編集

非常にご親切な回答、誠にありがとうございます。 ご助言を踏まえ、上記pyファイルを反映しましたところ、以下のエラーが発生しております。たびたび恐縮でございますが、解決策等、ございますでしょうか。 tensorflow.python.framework.errors_impl.FailedPreconditionError: Error while reading resource variable conv2d_10/kernel from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/conv2d_10/kernel) [[{{node conv2d_10/convolution/ReadVariableOp}}]]
can110

2020/02/16 02:42

どこで発生したのか不明なので何とも云えませんが エラーメッセージで検索すると何等かの情報が得られる可能性があります。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.46%

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

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

質問する

関連した質問