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

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

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

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

Anaconda

Anacondaは、Python本体とPythonで利用されるライブラリを一括でインストールできるパッケージです。環境構築が容易になるため、Python開発者間ではよく利用されており、商用目的としても利用できます。

OpenCV

OpenCV(オープンソースコンピュータービジョン)は、1999年にインテルが開発・公開したオープンソースのコンピュータビジョン向けのクロスプラットフォームライブラリです。

Python 3.x

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

Q&A

解決済

2回答

1649閲覧

定義済みの変数でなぜNameErrorがおこる?

Tello-python

総合スコア6

Keras

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

Anaconda

Anacondaは、Python本体とPythonで利用されるライブラリを一括でインストールできるパッケージです。環境構築が容易になるため、Python開発者間ではよく利用されており、商用目的としても利用できます。

OpenCV

OpenCV(オープンソースコンピュータービジョン)は、1999年にインテルが開発・公開したオープンソースのコンピュータビジョン向けのクロスプラットフォームライブラリです。

Python 3.x

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

0グッド

0クリップ

投稿2019/10/18 08:45

編集2019/10/19 11:39

python

1python -m tellopy.examples.video_effect

を実行すると以下のエラーが出ます

python

1Traceback (most recent call last): 2 File "C:\Users\one\Anaconda3\envs\py3.5\lib\site-packages\tellopy\examples\video_effect.py", line 92, in main 3 image = getSSDImage(imgpil) 4 File "C:\Users\one\Anaconda3\envs\py3.5\lib\site-packages\tellopy\examples\video_effect.py", line 65, in getSSDImage 5 score = top_conf[i] 6NameError: name 'i' is not defined 7name 'i' is not defined

video_effect.pyのコードはこちらです

python

1import cv2 2import keras 3from keras.applications.imagenet_utils import preprocess_input 4from keras.backend.tensorflow_backend import set_session 5from keras.models import Model 6from keras.preprocessing import image 7import matplotlib.pyplot as plt 8import numpy as np 9from scipy.misc import imread 10import tensorflow as tf 11from ssd_v2 import SSD300v2 12from ssd_utils import BBoxUtility 13from PIL import Image 14import sys 15import traceback 16import tellopy 17import av 18import numpy 19plt.rcParams['figure.figsize'] = (8, 8) 20plt.rcParams['image.interpolation'] = 'nearest' 21np.set_printoptions(suppress=True) 22config = tf.ConfigProto() 23config.gpu_options.per_process_gpu_memory_fraction = 0.45 24set_session(tf.Session(config=config)) 25voc_classes = ['Aeroplane', 'Bicycle', 'Bird', 'Boat', 'Bottle', 26'Bus', 'Car', 'Cat', 'Chair', 'Cow', 'Diningtable', 27'Dog', 'Horse','Motorbike', 'Person', 'Pottedplant', 28'Sheep', 'Sofa', 'Train', 'Tvmonitor'] 29NUM_CLASSES = len(voc_classes) + 1 30input_shape=(100, 100, 3) 31model = SSD300v2(input_shape, num_classes=NUM_CLASSES) 32model.load_weights('weights_SSD300.hdf5', by_name=True) 33bbox_util = BBoxUtility(NUM_CLASSES) 34def getSSDImage(frame): 35 global i 36 img2 = image.img_to_array(frame.resize((100, 100))) 37 img = np.asarray(frame) 38 inputs = [] 39 inputs.append(img2.copy()) 40 inputs = preprocess_input(np.array(inputs)) 41 preds = model.predict(inputs, batch_size=1, verbose=1) 42 results = bbox_util.detection_out(preds) 43 # Parse the outputs. 44 det_label = results[0][:, 0] 45 det_conf = results[0][:, 1] 46 det_xmin = results[0][:, 2] 47 det_ymin = results[0][:, 3] 48 det_xmax = results[0][:, 4] 49 det_ymax = results[0][:, 5] 50 # Get detections with confidence higher than 0.6. 51 top_indices = [i for i, conf in enumerate(det_conf) if conf >= 0.6] 52 top_conf = det_conf[top_indices] 53 top_label_indices = det_label[top_indices].tolist() 54 top_xmin = det_xmin[top_indices] 55 top_ymin = det_ymin[top_indices] 56 top_xmax = det_xmax[top_indices] 57 top_ymax = det_ymax[top_indices] 58 colors = plt.cm.hsv(np.linspace(0, 1, 21)).tolist() 59 for i in range(top_conf.shape[0]): 60 xmin = int(round(top_xmin[i] * img.shape[1])) 61 ymin = int(round(top_ymin[i] * img.shape[0])) 62 xmax = int(round(top_xmax[i] * img.shape[1])) 63 ymax = int(round(top_ymax[i] * img.shape[0])) 64 score = top_conf[i] 65 label = int(top_label_indices[i]) 66 label_name = voc_classes[label - 1] 67 display_txt = '{:0.2f}, {}'.format(score, label_name) 68 color = colors[label] 69 cv2.rectangle(img, (xmin, ymin), (xmax, ymax), (int(colors[label][0]*255), int(colors[label][1]*255), int(colors[label][2]*255)), 2) 70 cv2.rectangle(img, (xmin, ymin-15), (xmin+100, ymin+5), (int(colors[label][0]*255), int(colors[label][1]*255), int(colors[label][2]*255)),-1) 71 cv2.putText(img, display_txt, (xmin, ymin), cv2.FONT_HERSHEY_PLAIN, 1, (255, 255, 255), 1, cv2.LINE_AA) 72 imgcv = img[:, :, ::-1].copy() 73 return imgcv 74def main(): 75 drone = tellopy.Tello() 76 try: 77 drone.connect() 78 drone.wait_for_connection(60.0) 79 drone.set_loglevel(drone.LOG_INFO) 80 drone.set_exposure(0) 81 container = av.open(drone.get_video_stream()) 82 frame_count = 0 83 while True: 84 for frame in container.decode(video=0): 85 frame_count = frame_count + 1 86 if (frame_count > 300) and (frame_count%50 == 0): 87 imgpil = frame.to_image() 88 image = getSSDImage(imgpil) 89 90 cv2.imshow('Original', image) 91 cv2.waitKey(1) 92 except Exception as ex: 93 exc_type, exc_value, exc_traceback = sys.exc_info() 94 traceback.print_exception(exc_type, exc_value, exc_traceback) 95 print(ex) 96 finally: 97 drone.quit() 98 cv2.destroyAllWindows() 99if __name__ == '__main__': 100 main()

エラーで書かれている

python

1score = top_conf[i]

というコードより上に変数「i」が使用されているのにそこではエラーが出ません。
なぜなのでしょう?

またどのように解決するのでしょう
#環境
TelloPy:0.6.0
python:3.5
Keras:2.0.1
opencv-python:3.1.0.0
ssd:1.0.0

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

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

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

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

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

guest

回答2

0

自己解決

投稿2019/10/21 07:58

Tello-python

総合スコア6

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

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

0

関数 getSSDImage の中で、 global i と宣言しているのは、ここの iが グローバルであると言ってるだけで、関数の外に i が無いですね。
そして、 他の関数 (main)に、global i が無いので、mainの中では、未定義エラーとなります。
mainの中でも global iを定義し、関数の外にも i = 0(整数だったら)のように記述しておきましょう。

投稿2019/10/19 12:14

pepperleaf

総合スコア6383

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

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

Tello-python

2019/10/20 05:47

pepperleafさんのアドバイス通りmainの中、 drone = tellopy.Tello() の上の行にglobal iと記述して実行したのですが同じエラーが出ます... *補足 関係あるかわかりませんがGithubからTelloPyをダウンロードした際には関数(getSSDImage)の中に(global i)の宣言はなく、宣言がない状態で実行したところ Traceback (most recent call last): File "C:\Users\one\Anaconda3\envs\py3.5\lib\site-packages\tellopy\examples\video_effect.py", line 91, in main image = getSSDImage(imgpil) File "C:\Users\one\Anaconda3\envs\py3.5\lib\site-packages\tellopy\examples\video_effect.py", line 64, in getSSDImage score = top_conf[i] UnboundLocalError: local variable 'i' referenced before assignment local variable 'i' referenced before assignment というエラーが出たため関数(getSSDImage)の中で宣言(global i)しました。
pepperleaf

2019/10/20 14:22

申し訳ない、質問の意図を間違えていたようです。 i という変数が直前の for で使われているので、未定義変数というのもおかしいですね。 簡単なもので、同じエラー... と思ったのですが、再現しません。
Tello-python

2019/10/21 01:10

いえいえ、ご丁寧にありがとうございました!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問