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

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

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

YOLOとは、画像検出および認識用ニューラルネットワークです。CベースのDarknetというフレームワークを用いて、画像や動画からオブジェクトを検出。リアルタイムでそれが何になるのかを認識し、分類することができます。

Ubuntu

Ubuntuは、Debian GNU/Linuxを基盤としたフリーのオペレーティングシステムです。

Python

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

Q&A

解決済

1回答

1063閲覧

クラス化で困っています

reiya_123

総合スコア57

YOLO

YOLOとは、画像検出および認識用ニューラルネットワークです。CベースのDarknetというフレームワークを用いて、画像や動画からオブジェクトを検出。リアルタイムでそれが何になるのかを認識し、分類することができます。

Ubuntu

Ubuntuは、Debian GNU/Linuxを基盤としたフリーのオペレーティングシステムです。

Python

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

0グッド

0クリップ

投稿2021/09/13 02:06

編集2021/09/14 01:48

前提・実現したいこと

python3.8 ubuntu20.04 vscodeです。
realsenseによりyoloを起動していますが、classesに波線が入りclassesが認識されていない状態です。

該当のソースコード

import pyrealsense2 as rs import numpy as np import cv2 import sys from playsound import playsound # Initialize the parameters confThreshold = 0.5 nmsThreshold = 0.4 inpWidth = 416 inpHeight = 416 classesFile = "/home/limlab/realsense_yolo_v3_2d/coco.names" # Configure depth and color streams pipeline = rs.pipeline() config = rs.config() config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30) config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30) # Start streaming pipeline.start(config) class CAMDEMO: def __init__ (self): self.j = 0 def getOutputsNames(self,net): layersNames = net.getLayerNames() return [layersNames[i[0] -1] for i in net.getUnconnectedOutLayers()] #検出 def drawPredicted(self,classId, conf, left, top,right, bottom, frame,x,y): classes = None with open(classesFile, "rt") as f: classes = f.read().rstrip('\n').split('\n') cv2.rectangle(frame, (left,top), (right,bottom), (255,0,0),3)#囲み cv2.circle(frame,(x,y),radius=1,color=(0,255,0), thickness=5)#・ label = '%.2f' % conf if classes: assert(classId < len(classes)) label = '%s' %(classes[classId]) cv2.putText(frame, label,(left,top-5), cv2.FONT_HERSHEY_SIMPLEX,0.75,(255,255,0),2) global first#グローバル変数firstを定義 first = True #実行一回目がTrueの場合 if first == True: path = '/home/limlab/realsense_yolo_v3_2d/image/' if label == 'bottle': #labelがbottleの場合 self.j += 1 if self.j == 1:#def__init__()で0と定義している、0の場合実行 cv2.imwrite(path + 'image1.png',frame) print('ペットボトルを検出しました') playsound("/home/limlab/programs/bottle.mp3") self.j += 1#iの変数が1になる sys.exit() if label == 'mouse': self.j += 1 if self.j == 1: cv2.imwrite(path + 'image1.png',frame) print('マウスを検出しました') playsound("/home/limlab/programs/mouse.mp3") self.j += 1 sys.exit() labelSize= cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1) top = max(top, labelSize[1]) cv2.putText(frame, label,(left,top-5), cv2.FONT_HERSHEY_SIMPLEX,0.75,(0,255,0),2) def process_detection(self,frame, outs): frameHeight = frame.shape[0] frameWidth = frame.shape[1] classIds = [] confidences = [] boxes = [] for out in outs: for detection in out: scores = detection[5:] classId = np.argmax(scores) confidence = scores[classId] if confidence > confThreshold: center_x = int(detection[0]*frameWidth) center_y = int(detection[1]*frameHeight) width = int(detection[2]*frameWidth) height = int(detection[3]*frameHeight) left = int(center_x - width/2) top = int(center_y - height/2) classIds.append(classId) indices = cv2.dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold) for i in indices: i = i[0] box = boxes[i] left = box[0] top = box[1] width = box[2] height = box[3] x = int(left+width/2) y = int(top+ height/2) self.drawPredicted(classIds[i], confidences[i], left, top,left+width,top+height,frame,x,y) def main(): cam = CAMDEMO() modelConfiguration = "/home/limlab/realsense_yolo_v3_2d/yolov3.cfg" modelWeights = "/home/limlab/realsense_yolo_v3_2d/yolov3.weights" net = cv2.dnn.readNetFromDarknet(modelConfiguration, modelWeights) net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV) net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU) try: while True: # Wait for a coherent pair of frames: depth and color frames = pipeline.wait_for_frames() color_frame = frames.get_color_frame() if not color_frame: continue # Convert images to numpy arrays color_image = np.asanyarray(color_frame.get_data()) blob = cv2.dnn.blobFromImage(color_image, 1/255, (inpWidth, inpHeight), [0,0,0],1,crop=False) net.setInput(blob) outs = net.forward(cam.getOutputsNames(net)) # Apply colormap on depth image (image must be converted to 8-bit per pixel first) cam.process_detection(color_image,outs) images = color_image # Show images cv2.imshow('Yolo in RealSense made by Tony', images) if cv2.waitKey(1) & 0xFF == ord('q'): break finally: # Stop streaming pipeline.stop() if __name__ == "__main__": main()

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

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

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

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

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

p19ljk

2021/09/13 03:02 編集

認識されていないというのはdrawPredicted内のclassesのことですか? CAMDEMO内で定義されていないので当然かと思いますが。 (main関数内は別スコープ)
reiya_123

2021/09/13 07:22

クラス化する前から以下のようにclassesを定義しているところが見つからないのですがなぜでしょうか。 申し訳ございませんが教えていただけませんでしょうか confThreshold = 0.5 nmsThreshold = 0.4 inpWidth = 416 inpHeight = 416 classesFile = "/home/limlab/realsense_yolo_v3_2d/coco.names" # Configure depth and color streams pipeline = rs.pipeline() config = rs.config() config.enable_stream(rs.stream.depth, 640, 480, rs.format.z16, 30) config.enable_stream(rs.stream.color, 640, 480, rs.format.bgr8, 30) # Start streaming pipeline.start(config) def getOutputsNames(net): layersNames = net.getLayerNames() return [layersNames[i[0] -1] for i in net.getUnconnectedOutLayers()] #検出 def drawPredicted(classId, conf, left, top, right, bottom, frame,x ,y): cv2.rectangle(frame, (left,top), (right,bottom), (255,0,0),3)#囲み cv2.circle(frame,(x,y),radius=1,color=(0,255,0), thickness=5)#・ label = '%.2f' % conf if classes: label = '%s' %(classes[classId])
p19ljk

2021/09/13 23:58

そのコードはもともとどこにあったものですかね? main関数の中です?
guest

回答1

0

ベストアンサー

元ソースは

python

1if __name__ == "__main__": 2 classes = None 3 with open(classesFile, "rt") as f: 4 classes = f.read().rstrip('\n').split('\n')

と[if name == "main":]内でclassesを定義していますね。
そして質問者さんはこの部分をmain関数に切り出して

python

1def main(): 2 classes = None 3 with open(classesFile, "rt") as f: 4 classes = f.read().rstrip('\n').split('\n') 5 6if __name__ == "__main__": 7 main()

としています。(あれ、main関数の中身最初と変わってる?)
ここで、一見分かりづらいですが[if name == "main":]の中で定義されている変数はグローバル変数となります。
なので元のソースでは問題ありません。
しかしmain関数内に切り出した時点でこれはmain関数内のローカル変数となってしまい、関数外のclassesは未定義のエラーが出てしまいます。
同じようにしたいのであれば

python

1classes = None

はmain関数の外(confThreshold とかの並び)に記述してみてください。

投稿2021/09/14 07:21

p19ljk

総合スコア146

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問