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

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

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

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

Anaconda

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

YOLO

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

OpenCV

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

Python

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

Q&A

0回答

1206閲覧

YOLOv3での検出範囲選択(マウスイベント)

cpxeon02

総合スコア0

Keras

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

Anaconda

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

YOLO

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

OpenCV

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

Python

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

0グッド

0クリップ

投稿2021/12/16 19:55

編集2021/12/17 02:15

前提・実現したいこと

YOLOv3(keras版)を改良し,マウスイベントを用いて物体の検出範囲が指定できるようにしたいです。
そこで,下記リンクのソースコードを参考にyolo.pyに書き足す形で考えたのですが,どの辺りを変更していいのかがわかりません。

マウスイベント参考先↓
https://qiita.com/otakoma/items/04e525ac74b7191dffe6

リアルタイムでの実装を想定しているため
動画読み込む→物体検出→マウスでエリア(台形)を指定→検出された物体のエリア内外判定
という流れで動作することが理想です。

※ご指摘頂いた通り、この流れだとマウスでエリアを指定している間は読み込んだ動画が流れていってしまいます。リアルタイムでの長時間の検出が目的な為、動画が流れてしまっても大丈夫です。

検出した物体のエリア内外判定についてはopen cvの関数「PointPolygonTest」を用いて実装する予定です

該当のソースコード

Python

1# -*- coding: utf-8 -*- 2""" 3Class definition of YOLO_v3 style detection model on image and video 4""" 5 6import colorsys 7import os 8from timeit import default_timer as timer 9import cv2 10 11import numpy as np 12from keras import backend as K 13from keras.models import load_model 14from keras.layers import Input 15from PIL import Image, ImageFont, ImageDraw 16from tensorflow.python.ops.gen_array_ops import fill 17 18from yolo3.model import yolo_eval, yolo_body, tiny_yolo_body 19from yolo3.utils import letterbox_image 20import os 21from keras.utils import multi_gpu_model 22 23class YOLO(object): 24 _defaults = { 25 "model_path": 'model_data/yolo.h5', 26 "anchors_path": 'model_data/yolo_anchors.txt', 27 "classes_path": 'model_data/coco_classes.txt', 28 "score" : 0.3, 29 "iou" : 0.45, 30 "model_image_size" : (416, 416), 31 "gpu_num" : 1, 32 } 33 34 @classmethod 35 def get_defaults(cls, n): 36 if n in cls._defaults: 37 return cls._defaults[n] 38 else: 39 return "Unrecognized attribute name '" + n + "'" 40 41 def __init__(self, **kwargs): 42 self.__dict__.update(self._defaults) # set up default values 43 self.__dict__.update(kwargs) # and update with user overrides 44 self.class_names = self._get_class() 45 self.anchors = self._get_anchors() 46 self.sess = K.get_session() 47 self.boxes, self.scores, self.classes = self.generate() 48 49 def _get_class(self): 50 classes_path = os.path.expanduser(self.classes_path) 51 with open(classes_path) as f: 52 class_names = f.readlines() 53 class_names = [c.strip() for c in class_names] 54 return class_names 55 56 def _get_anchors(self): 57 anchors_path = os.path.expanduser(self.anchors_path) 58 with open(anchors_path) as f: 59 anchors = f.readline() 60 anchors = [float(x) for x in anchors.split(',')] 61 return np.array(anchors).reshape(-1, 2) 62 63 def generate(self): 64 model_path = os.path.expanduser(self.model_path) 65 assert model_path.endswith('.h5'), 'Keras model or weights must be a .h5 file.' 66 67 # Load model, or construct model and load weights. 68 num_anchors = len(self.anchors) 69 num_classes = len(self.class_names) 70 is_tiny_version = num_anchors==6 # default setting 71 try: 72 self.yolo_model = load_model(model_path, compile=False) 73 except: 74 self.yolo_model = tiny_yolo_body(Input(shape=(None,None,3)), num_anchors//2, num_classes) \ 75 if is_tiny_version else yolo_body(Input(shape=(None,None,3)), num_anchors//3, num_classes) 76 self.yolo_model.load_weights(self.model_path) # make sure model, anchors and classes match 77 else: 78 assert self.yolo_model.layers[-1].output_shape[-1] == \ 79 num_anchors/len(self.yolo_model.output) * (num_classes + 5), \ 80 'Mismatch between model and given anchor and class sizes' 81 82 print('{} model, anchors, and classes loaded.'.format(model_path)) 83 84 # Generate colors for drawing bounding boxes. 85 hsv_tuples = [(x / len(self.class_names), 1., 1.) 86 for x in range(len(self.class_names))] 87 self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples)) 88 self.colors = list( 89 map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)), 90 self.colors)) 91 np.random.seed(10101) # Fixed seed for consistent colors across runs. 92 np.random.shuffle(self.colors) # Shuffle colors to decorrelate adjacent classes. 93 np.random.seed(None) # Reset seed to default. 94 95 # Generate output tensor targets for filtered bounding boxes. 96 self.input_image_shape = K.placeholder(shape=(2, )) 97 if self.gpu_num>=2: 98 self.yolo_model = multi_gpu_model(self.yolo_model, gpus=self.gpu_num) 99 boxes, scores, classes = yolo_eval(self.yolo_model.output, self.anchors, 100 len(self.class_names), self.input_image_shape, 101 score_threshold=self.score, iou_threshold=self.iou) 102 return boxes, scores, classes 103 104 105 def detect_image(self, image): 106 import cv2 107 start = timer() 108 109 if self.model_image_size != (None, None): 110 assert self.model_image_size[0]%32 == 0, 'Multiples of 32 required' 111 assert self.model_image_size[1]%32 == 0, 'Multiples of 32 required' 112 boxed_image = letterbox_image(image, tuple(reversed(self.model_image_size))) 113 else: 114 new_image_size = (image.width - (image.width % 32), 115 image.height - (image.height % 32)) 116 boxed_image = letterbox_image(image, new_image_size) 117 image_data = np.array(boxed_image, dtype='float32') 118 119 print(image_data.shape) 120 image_data /= 255. 121 image_data = np.expand_dims(image_data, 0) # Add batch dimension. 122 123 out_boxes, out_scores, out_classes = self.sess.run( 124 [self.boxes, self.scores, self.classes], 125 feed_dict={ 126 self.yolo_model.input: image_data, 127 self.input_image_shape: [image.size[1], image.size[0]], 128 K.learning_phase(): 0 129 }) 130 131 print('Found {} boxes for {}'.format(len(out_boxes), 'img')) 132 133 font = ImageFont.truetype(font='font/FiraMono-Medium.otf', 134 size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32')) 135 thickness = (image.size[0] + image.size[1]) // 300 136 137 for i, c in reversed(list(enumerate(out_classes))): 138 predicted_class = self.class_names[c] 139 if predicted_class == 'person': 140 box = out_boxes[i] 141 score = out_scores[i] 142 143 label = '{} {:.2f}'.format(predicted_class, score) 144 draw = ImageDraw.Draw(image) 145 label_size = draw.textsize(label, font) 146 147 top, left, bottom, right = box 148 top = max(0, np.floor(top + 0.5).astype('int32')) 149 left = max(0, np.floor(left + 0.5).astype('int32')) 150 bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32')) 151 right = min(image.size[0], np.floor(right + 0.5).astype('int32')) 152 print(label, (left, top), (right, bottom)) 153 154 if top - label_size[1] >= 0: 155 text_origin = np.array([left, top - label_size[1]]) 156 else: 157 text_origin = np.array([left, top + 1]) 158 159 # My kingdom for a good redistributable image drawing library. 160 for i in range(thickness): 161 draw.rectangle( 162 [left, top, right, bottom], 163 outline=self.colors[c]) 164 draw.rectangle( 165 [tuple(text_origin), tuple(text_origin + label_size)], 166 fill=self.colors[c]) 167 draw.text(text_origin, label, fill=(0, 0, 0), font=font) 168 del draw 169 170 end = timer() 171 print(end - start) 172 return image 173 174 def close_session(self): 175 self.sess.close() 176 177def detect_video(yolo, video_path, output_path=""): 178 vid = cv2.VideoCapture(video_path) 179 if not vid.isOpened(): 180 raise IOError("Couldn't open webcam or video") 181 video_FourCC = int(vid.get(cv2.CAP_PROP_FOURCC)) 182 video_fps = vid.get(cv2.CAP_PROP_FPS) 183 video_size = (int(vid.get(cv2.CAP_PROP_FRAME_WIDTH)), 184 int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))) 185 isOutput = True if output_path != "" else False 186 if isOutput: 187 print("!!! TYPE:", type(output_path), type(video_FourCC), type(video_fps), type(video_size)) 188 out = cv2.VideoWriter(output_path, video_FourCC, video_fps, video_size) 189 accum_time = 0 190 curr_fps = 0 191 fps = "FPS: ??" 192 prev_time = timer() 193 while True: 194 return_value, frame = vid.read() 195 image = Image.fromarray(frame) 196 image = yolo.detect_image(image) 197 result = np.asarray(image) 198 curr_time = timer() 199 exec_time = curr_time - prev_time 200 prev_time = curr_time 201 accum_time = accum_time + exec_time 202 curr_fps = curr_fps + 1 203 if accum_time > 1: 204 accum_time = accum_time - 1 205 fps = "FPS:" + str(curr_fps) 206 curr_fps = 0 207 cv2.putText(result, text=fps, org=(3, 15), fontFace=cv2.FONT_HERSHEY_SIMPLEX, 208 fontScale=0.30, color=(255, 0, 0), thickness=1) 209 cv2.namedWindow("result", cv2.WINDOW_NORMAL) 210 cv2.imshow("result", result) 211 if isOutput: 212 out.write(result) 213 if cv2.waitKey(1) & 0xFF == ord('q'): 214 break 215 yolo.close_session() 216

補足情報

yolov3 - https://github.com/qqwweee/keras-yolo3

環境
・Anaconda / Python 3.7
・keras 2.2.4
・tensorflow 1.13.1
・matplotlib
・pillow
・OpenCV

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

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

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

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

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

退会済みユーザー

退会済みユーザー

2021/12/16 21:22

YOLOの推論結果をベースに、アノテーション結果を修正するようなツールを作りたいという意味でしょうか? ご存知と思いますが、動画はパラパラ漫画と同じでリアルタイムに画像を差し替えていく処理をしています。マウスで領域選択をする間も画像が差し替えられていくと思うのでこの辺りをどうしたいか明記した方がいいと思います。
cpxeon02

2021/12/17 02:07

コメントありがとうございます。 追記させて頂きます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問