tinyYOLOv2を軽く実装してみる
tinyYOLOv2軽く実装
tinyYOLOv2について少し調べたので少しだけ書こうと思います。
実装は以下のURLのものを使いました。
環境:Python3, tensorflow 1.0, numpy, opencv 3.
githubから以下のzipファイルをダウンロードします。
https://github.com/thtrieu/darkflow/archive/master.zip
サイトのREADME.mdの指示通りやります。
まずDependenciesのgetting startedより
/darkflow-masterで
python3 setup.py build_ext --inplace
を実行してdarkflowをインストールします。
転移学習(事前に学習を行ってあるモデル)を用意します。
以下の2つのファイルをダウンロードします。
https://github.com/pjreddie/darknet/blob/master/cfg/yolov2-tiny.cfg
https://pjreddie.com/media/files/yolov2-tiny.weights
githubを見るとcfgファイルを/cfg、weightファイルを/binに保存しているようなのでファイルを作って保存をしました。
またこの学習済みモデルは20クラスの分類データなのでラベルファイルlabel.txtを
aeroplane
bicycle
bird
bottle
bus
car
cat
chair
cow
diningtable
dog
horse
motorbike
person
pottedplant
sheep
sofa
train
tvmonitor
のように書き換えます。
githubのUsing darkflow from another python applicationを参考にしながら以下のようにpythonファイルを書きます。
ここではcocoa.pyとします。
from darkflow.net.build import TFNet import cv2 options = {"model": "yolov2-tiny.cfg", "load": "bin/yolov2-tiny.weights", "threshold": 0.5} tfnet = TFNet(options) imgcv = cv2.imread("./sample_img/sample_dog.jpg") result = tfnet.return_predict(imgcv) print(result)
テスト画像はこのような写真です。
https://github.com/thtrieu/darkflow/blob/master/sample_img/sample_dog.jpg
以下のコマンドを実行します。
バージョンによっては以下のようなエラーが発生します。
AssertionError: expect 44948596 bytes, found 44948600
もしこのエラーが出たら/darkflow/utils/loader.pyのself.offset = 16をself.offset = 20に書き換えます。
それでもエラーが出たらさらにcfg/yolov2-tiny.cfgの125行目classes=80をclasses=20に変更します。
実行すると以下のように表示されます。
[{'label': 'bicycle', 'confidence': 0.84314215, 'topleft': {'x': 46, 'y': 92}, 'bottomright': {'x': 595, 'y': 482}}, {'label': 'bird', 'confidence': 0.6847313, 'topleft': {'x': 454, 'y': 85}, 'bottomright': {'x': 668, 'y': 165}}]
ここではbicycleとbirdが見つかったことを示しています(犬がいない...w)。