使用するGoogle object_detection APIの重力波検出器

前回の記事で、私は、仮想のenvの下にインストールおよび使用方法のtensorflowフレームワークを導入しています。私の卒業プロジェクトですが、また、私は最初の実用的な機械学習とtensorflowフレーム期間の後に行うことを学んでいるこのブログの下に。あなたはこの記事が親しみなることを安心することができますので、あまり多くはないが、アルゴリズムを導入している(私はここにネットワーク構造を使用し、私はあなたにタグネットワーク構造の詳細な導入とアルゴリズム解析では得られます)。

プロジェクトの簡単な紹介

あなたは私のブログを約で読めば、あなたは私が物理学関連の学生だということを知っている必要があります。私の卒業プロジェクトは、自動的に衛星画像からの重力波を検出することが主な理由です。ここでは衛星画像でリーダーだけで一般的な概念を持つように、重力波の特定の意味を知っている必要はありません、大気重力波は、おそらくこれです:
重力波の画像
私たちは目標を説明する必要がこのような重力波構造は、下の画像に自動的に認識しましたコンテンツは、それが特定されたオブジェクト検出を使用する方法です。

簡単でtensorflow物体検出API

実際には、githubの上で知っておくべきtensorflow、tensorflowホームページに精通し、人々は次のとおりです。tensorflow tensorflow / tensorflow、他:、この家は2レポ(星の数を参照することができます)、Tensorflowソースコードのレポです以下のより重要なを持っています一つは、我々がtensorflow /モデルを導入しなければならないということです。後者tensorflow /モデルは、今日の、より重要なの私たちの練習のトピックを行うにはTensorFlowと、Googleの公式の様々な例であり、画像分類スリムです。特に米国今、このタスクのために、そのようなVGG6、ResNet及び他のネットワーク構造として、いわゆる特徴抽出(特徴抽出)層として作用するようにまともなImageNet画像分類モデルが先行されなければなりません。これらのプロジェクトを達成するためにtensorflow公式ネットワーク構造がスリムtensorflowで、物体検出APIをスリムに基づいて、コンテンツが比較的豊富で、成熟し、以前このライブラリの時間を発表しました。ここで私は、インストールからトレーニングまで、予測した後、あなたは命令が説明する詳細な与えます。

tensorflow /モデルのインストール

まず、我々はgithubのモデルの設置の勧告を参照することができレポ:
最初は、ライブラリの依存関係の状況です:

  • いるProtobuf 3+
  • Pythonの-TK(マップはmatplotlibのと競合可能性がある場合、ライブラリの後ろにバックエンドを見るためにそうするように)
  • 枕1.0
  • lxmlの(私たちのデータセットで使用されるデータ形式を識別するためのパスカルVOCの順序、我々はライブラリをインストールする必要があります。)
  • スリム(すでにこのライブラリtenorflow /モデル/ ersearch /内部に含まれ、1つの命令のみが抽出スリムを指定することができます)
  • jupyterノートブック(良いインターフェースを提供pythonの便利なビジュアルプログラミングツール、ボーエンプログラミング環境のディレクトリ私はanaconda3 + jupyter遠隔操作を使用する方法について説明します)
  • matplotlibの(絵画ギャラリー、説明していません)
  • tensorflow
  • cython
  • cocoapi

あなたのマシンがすでにtensoflowがインストールされていない場合は、tensorflowインストールした私の以前の記事を参照してください。(ネイティブ環境ubuntu16.04 + python3.5.2仮想ENVを使用)、上述ここで依存ライブラリをインストールする方法です。

sudo apt-get install protobuf-compiler python-pil python-lxml python-tk
sudo pip install Cpython
sudo pip install jupyter
sudo pip install matplotlib

あなたのマシンは、aptパッケージ管理システムとしてのUbuntuやDebianを使用していない場合はもちろん、あなたも直接ピップを(清華ミラー化ソリューションは、本土遅いダウンロードに-iフラグを添加して使用することができる状況を高速化)をインストールすることを選択することができます。

sudo pip install Cython
sudo pip install pillow
sudo pip install lxml
sudo pip install jupyter
sudo pip install matplotlib

こちらのモデル私はあなたしている興味があれば、あなたは遊びダウンgithubのクローンCOCOに直接行くことができるので、何もインストールCOCO COCOのAPIライブラリがありません使用していませんでしたので。
上記の依存関係の完了をインストールした後、我々は、githubのクローンダウンにモデルライブラリを直接ディレクトリtensorflow /モデル/研究にcdとディレクトリにインストールのpythonを実行します:

python setup.py build
python setup.py install

我々は物体検出APIは、モデルやトレーニングパラメータをコンパイルするために使用されいるProtobuf使用しているため、またtensorflow /モデル/研究コンパイルいるProtobufライブラリを必要とする、それがあります。お使いのマシンがいるProtobufインストールされていない場合は、コンパイルしてインストールしてください、エラーが発生した後にインストールされている場合(あなたが知っていれば、私は、非常に明確ではないです理由に関するエラー、私に知らせてください):

object_detection/protos/anchor_generator.proto:11:3:  Expected “required”, “optional”, or “repeated”.
object_detection/protos/anchor_generator.proto:11:32: Missing field number. 

ソリューションいるProtobufコンパイルされたファイルのダウンロードですダウンロードを binフォルダにファイルを解凍するためにtensorfolw protoc_3.3フォルダにアーカイブ解凍し、

cd bin/
pwd(这一步是为了记住你的bin文件夹全地址)
cd ...你的tenforflow地址.../models/
/home/gabrielsun/tensorflow/protoc3.3/bin/protoc objecr_detection/protos/*.proto --python_out=.

この方法では、正常いるProtobufクリップをコンパイルした一般的な研究ファイルで成功することができます。問題がある場合、私はコメント欄にメッセージを残すことができます。
今、私たちは、標的認識のようにスリム指定する必要があり、ここにあなたがこのコード行が含まれていない場合は、〜/ .bashrcのファイルに書き込まれていることは注目に値するが、その後、それぞれが新しい端末が研究フォルダに次のコードを実行必要があります:

export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim 

最後に、インストールがコンパイルされているかどうかをテストするには:

 python object_detection/builders/models_builder_test.py

出力がOKであれば、それはテストです。
だから、私たちの取付部が終わったことを!主なプログラミング環境はまた、我々は、データセットの構築を議論し、次のように良いを構築しました。

の生産データの収集

この部分はI適切に考慮されていないの未解決の問題の前に私の卒業プロジェクトの実際の部分、これはまた後ほどこのセクションでは、私は多くの時間と労力を費やしたためにつながる可能性があります。ここでは簡単な説明があります。私の考えはそう画像をマークするためにどのように大きな問題であり、目標検出などの画像データを使用することです。-pascal VOC形式マーキングの同一の画像データセットに実施例imagenetで採用I番号。このフォーマットは含まれています:

  • (写真は、トレーニングとテスト画像、混合一緒に含まれている)フォルダの画像
  • Annatationsフォルダ(XML形式のラベルファイル)
  • (このプロジェクトで使用されていない)画像セットフォルダ

私は今、衛星画像は、NOAAのWebサイト上でオリジナルのファイル形式のHDF5をダウンロードするには、その後、コードのペイントを書く(バンドによる問題にもコントラストを調整しますが、私は私が10 ^ 9を乗じたHDF5の値を放射輝度ますもっと怠け者だ)ので、そして、このプロセスは、誰も3チャンネルの画像にグレースケール画像(一般のみトレーニングワーク3チャンネルの画像を行うことができ、もちろん、あなたはまた、独自のモデルの完全なトレーニンググレースケール画像を書き込むことができobject_detectionライブラリのtensorflowを覚えている)ではありません私がちょうどトレーニングをしようとするならば、あなたは、インターネット上でいくつかの画像データをダウン独自の爬虫類の上昇を書き込み、またはビデオショットを使用できることを示唆しているように、我々はインターバルトレーニングデータにちょうど罰金を行うのですか、行うことが必要です。
あなたのためのコードのスクリーンショットを添付:

import cv2
cap = cv2.VIdeoCapture(“video.mp4”)
c = 1
timef = 100     #每100帧保存一张图像
while True;
    rval,frame = cap.read()
    if(c % timef == 0):
        print(‘tot=’,tot)
        cv2imwrite(‘out/‘+str(tot).zfill(6)+’.jpg’,frame)       
        tot = tot +1
    c+=1
    cv2.waitKey(1)
cap.release()

このような私たちの画像のコンテンツフォルダは、おそらく準備ができて、次の説明画像アノテーション作業がフォルダ注釈の内容を取得することであり、ここで私はlabelImgソリューションを行うには注釈を使用することで、あなたはGitHubの上で直接検索することができますlabelImg、これは、グラフィカルイメージマークアップツールで、画像にバウンディングボックスラベルされたターゲットを使用することができます。以下は、最も簡単なインストールの1について説明します。
依存ライブラリをインストールする必要があるかどうかを確認し、そして直接インストール、私の環境では、ローカルにクローンレポubuntu16.04のpython3 + Qt5、最初のgithubのある、そして実行します。

sudo apt-get install pyqt-dev-tools
sudo pip3 install lxml
python3 labelImg.py

そして、それは、標識の前に、選択したディレクトリに保存されているGUIインタフェース、優れた注目のアノテーションを使用して、より長いラベルです。私たちは、おそらく、張は次のようになり、生成されたXMLファイルは見ることができます:

<annotation>
    <folder>images</folder>
    <filename>0032.png</filename>
    <path>/home/gabrielsun/Desktop/images/0032.png</path>
    <source>
        <database>Unknown</database>
    </source>
    <size>
        <width>651</width>
        <height>520</height>
        <depth>1</depth>
    </size>
    <segmented>0</segmented>
    <object>
        <name>waves</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>204</xmin>
            <ymin>170</ymin>
            <xmax>317</xmax>
            <ymax>291</ymax>
        </bndbox>
    </object>
    <object>
        <name>waves</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>355</xmin>
            <ymin>274</ymin>
            <xmax>423</xmax>
            <ymax>466</ymax>
        </bndbox>
    </object>
    <object>
        <name>waves</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>489</xmin>
            <ymin>168</ymin>
            <xmax>587</xmax>
            <ymax>298</ymax>
        </bndbox>
    </object>
    <object>
        <name>waves</name>
        <pose>Unspecified</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>290</xmin>
            <ymin>68</ymin>
            <xmax>427</xmax>
            <ymax>161</ymax>
        </bndbox>
    </object>
</annotation>

しかし、私たちパスカルVOC形式のデータセットは、直接物体検出API、TFrecord形式に最初のデータのために使用されていません。TFrecordファイルは、メモリのより有効に活用するコピーして、より簡単に移動できるバイナリファイル、およびトランスコード添付がない別のタグファイルです:

import os
import io
import xml.etree.ElementTree as ET
import tensorflow as tf

from object_detection.utils import dataset_util
from PIL import Image


flags = tf.app.flags
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
flags.DEFINE_string('images_dir', '', 'Path to directory of images')
flags.DEFINE_string('labels_dir', '', 'Path to directory of labels')
FLAGS = flags.FLAGS


def create_tf_example(example):

    image_path = os.getcwd() + '/' + FLAGS.images_dir + example
    labels_path = os.getcwd() + '/' + FLAGS.labels_dir + \
        os.path.splitext(example)[0] + '.xml'

    # Read the image
    img = Image.open(image_path)
    width, height = img.size
    img_bytes = io.BytesIO()
    img.save(img_bytes, format=img.format)

    height = height
    width = width
    encoded_image_data = img_bytes.getvalue()
    image_format = img.format.encode('utf-8')

    # Read the label XML
    tree = ET.parse(labels_path)
    root = tree.getroot()
    xmins = xmaxs = ymins = ymaxs = list()

    for coordinate in root.find('object').iter('bndbox'):
        xmins = [int(coordinate.find('xmin').text) / width]
        xmaxs = [int(coordinate.find('xmax').text) / width]
        ymins = [int(coordinate.find('ymin').text) / height]
        ymaxs = [int(coordinate.find('ymax').text) / height]

    classes_text = ['waves'.encode('utf-8')]
    classes = [1]

    tf_example = tf.train.Example(features=tf.train.Features(feature={
        'image/height': dataset_util.int64_feature(height),
        'image/width': dataset_util.int64_feature(width),
        'image/filename': dataset_util.bytes_feature(encoded_image_data),
        'image/source_id': dataset_util.bytes_feature(encoded_image_data),
        'image/encoded': dataset_util.bytes_feature(encoded_image_data),,
        'image/format': dataset_util.bytes_feature(image_format),
        'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),
        'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),
        'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),
        'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),
        'image/object/class/text': dataset_util.bytes_list_feature(classes_text),
        'image/object/class/label': dataset_util.int64_list_feature(classes),
    }))
    return tf_example


def main(_):
    writer = tf.python_io.TFRecordWriter(FLAGS.output_path)

    for filename in os.listdir(FLAGS.images_dir):
        tf_example = create_tf_example(filename)
        writer.write(tf_example.SerializeToString())

    writer.close()


if __name__ == '__main__':
    tf.app.run()

実行します。

python3 convert_labels_to_tfrecords.py \ 
--output_path=train.record \ 
--images_dir=path/to/your/training/images/ \
--labels_dir=path/to/your/training/label/xml/

このようなデータのトレーニングセットはtfrecord、指定val.recordに画像や注釈の検証セットを合わせた後、フォーマットtfrecordに変換されています。だから、我々のデータセットの準備ができている場合でも。

トレーニングと予測モデル

私たちの研究の作業ディレクトリの一部としてディレクトリ内に2018420新しいディレクトリが、その主に将来のバージョン管理を容易にするために命名します。以前に生成された2 tfrecordは、このディレクトリにファイルを置きます。object_detection /データ/ pet_label_map.pbtxtに加えて、object_detection /サンプル/のconfigs / faster_rfcnn_resnet152_pets.configはまた、このディレクトリにこれら2つのファイルをコピーします。
私たちは、直接自分の状況に応じて調整されるように、設定ファイルに設定を使用することはできません。調整可能なパラメータは、超手順、学習率などが挙げられます。また、ファイルIOアドレスを調整します。私の練習の過程で、私は、最適な設定空にする、またはfalseに設定from_detection_checkpointパラメータfine_tune_checkpointを発見しました。
その後、我々は訓練を始めることができます。研究のディレクトリフォルダへの第1のスイッチと、その後、実行します。

python3 object_detection/train.py \ 
--logtostderr \ 
-- pipeline_config_path=‘./20180420/faster_rcnn_resnet152_pets.config’ \
--train_dir=‘./20180420/

だから、通常の状況下では、当社のトレーニングプロセスを開始することができます。しかし、私は可能なエラーバイトのオブジェクトと文字列の変換はなった操作の文字で実際にpython2のpython3と矛盾している実際の動作、に表示されますtensorflowインストールpython3.5.2を発見しました。python2文字列操作は、運転中に、関連するコードを実行するには私たちに参加しようとするオブジェクトのバイトに文字列のことですが、実際は除くことが必要である直接操作のpython3文字列、です。しかし、私はまだエラーになります期待し、私が直接tensorflow python2の下に設置使用する方法のため、怠惰を盗んだので、エラー・スタックは、直接変換さtensorflowすることができアナコンダを使用して、長すぎる、関連する試みを追加しました使用パイソン>インタープリタバージョン〜

私たちの結果の最初のを見てみましょう:
業績
あなたは外にトレーニングプロセスの可視化を実行するトレーニングプログラムの最後にtensorboardを使用することができます。
プロセスの可視化
我々はまた、訓練されたネットワークを評価するために選択することができますバック:

python3 object_detection/eval.py \ 
--logtostderr \
--pipeline_config_path=‘./20180420/faster_rcnn_resnet152_pets.config’ \ 
--checkpojint_dir=‘./20180420‘
--eval_dir=‘./20180420’ 

私の話はほとんど店や負荷モデルの終了前に、tensorflowが店に二つの方法を提供し、モデルをロード:
1.チェックポイントファイル(チェックポイントファイル)を生成し、拡張子がtf.train_saverオブジェクトによって、一般的に.ckptですコールSaver.save()世代に。なお、構造は図に含まれていない場合、プログラムで定義された量および他の変数を含んでいます。あなたが別のプログラムで使用する必要がある場合は、グラフ構造を再作成、および体重をどのように扱うかtensorflow指示する必要があります。
プロトコルファイル(グラフプロト・ファイル)を生成2.図は、拡張は、これはバイナリファイルであり、一般.pbあります。tf.train.write_graphを得ている()は、唯一のグラフ構造は重量を含まない、次いでtf.import_graph_def()パターンをロードするために含まれています。
このモデルは、ストレージおよびストレージの両方が、我々は検出アルゴリズムを作成したい場合は、それを取り出し、私にはモデル検出コードを読み取ることができない、相補的です。このように、我々は、モデル.pbファイルの生成を説明することができます:

python3 object_detection/export_inference_graph.py \ 
--input_type image_tensor
--pipeline_config_path=./2018420/faster_rcnn_resnet152_pets.config
--trained_checkpoint_prefix=./2018420/model.ckpt-1812 
--output_directory=./2018420/output_inference_graph 

私は私の予測コードを囲みます。

import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile

from collections import defaultdict
from io import StringIO
# from matplotlib import pyplot as plt ### CWH
from PIL import Image

# if tf.__version__ != '1.4.0':
#   raise ImportError('Please upgrade your tensorflow installation to v1.4.0!')

# ENV SETUP  ### CWH: remove matplot display and manually add paths to references
'''
# This is needed to display the images.
%matplotlib inline
# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")
'''

# Object detection imports

from object_detection.utils import label_map_util  # CWH: Add object_detection path

# from object_detection.utils import visualization_utils as vis_util ### CWH: used for visualization

# Model Preparation

# What model to download.
# MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17'
# MODEL_FILE = MODEL_NAME + '.tar.gz'
# DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'

# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = '/home/gabrielsun/tensorflow_python2.7/models/research/2018422/output_inference_graph/frozen_inference_graph.pb'

# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('/home/gabrielsun/tensorflow_python2.7/models/research/2018422',
                              'pet_label_map.pbtxt')  # CWH: Add object_detection path

NUM_CLASSES = 1


# Download Model
# opener = urllib.request.URLopener()
# opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)
# tar_file = tarfile.open(MODEL_FILE)
# for file in tar_file.getmembers():
#   file_name = os.path.basename(file.name)
#   if 'frozen_inference_graph.pb' in file_name:
#     tar_file.extract(file, os.getcwd())


# Load a (frozen) Tensorflow model into memory.
detection_graph = tf.Graph()
with detection_graph.as_default():
  od_graph_def = tf.GraphDef()
  with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
    serialized_graph = fid.read()
    od_graph_def.ParseFromString(serialized_graph)
    tf.import_graph_def(od_graph_def, name='')

# Loading label map
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(
    label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)


# Helper code
def load_image_into_numpy_array(image):
  (im_width, im_height) = image.size
  return np.array(image.getdata()).reshape(
      (im_height, im_width, 3)).astype(np.uint8)


# Detection
# For the sake of simplicity we will use only 2 images:
# image1.jpg
# image2.jpg
# If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.
PATH_TO_TEST_IMAGES_DIR = '/home/gabrielsun/Documents/Graduation_Design/code_and_data/dataset_train/images/'  # cwh
TEST_IMAGE_PATHS = [os.path.join(
    PATH_TO_TEST_IMAGES_DIR, '00{}.png'.format(i)) for i in range(45, 46)]

# Size, in inches, of the output images.
IMAGE_SIZE = (12, 8)

with detection_graph.as_default():
  with tf.Session(graph=detection_graph) as sess:
    # Definite input and output Tensors for detection_graph
    image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
    # Each box represents a part of the image where a particular object was detected.
    detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
    # Each score represent how level of confidence for each of the objects.
    # Score is shown on the result image, together with the class label.
    detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
    detection_classes = detection_graph.get_tensor_by_name(
        'detection_classes:0')
    num_detections = detection_graph.get_tensor_by_name('num_detections:0')
    for image_path in TEST_IMAGE_PATHS:
      image = Image.open(image_path)
      # the array based representation of the image will be used later in order to prepare the
      # result image with boxes and labels on it.
      image_np = load_image_into_numpy_array(image)
      # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
      image_np_expanded = np.expand_dims(image_np, axis=0)
      # Actual detection.
      (boxes, scores, classes, num) = sess.run(
          [detection_boxes, detection_scores, detection_classes, num_detections],
          feed_dict={image_tensor: image_np_expanded})

      # CWH: below is used for visualizing with Matplot
      '''
      # Visualization of the results of a detection.
      vis_util.visualize_boxes_and_labels_on_image_array(
          image_np,
          np.squeeze(boxes),
          np.squeeze(classes).astype(np.int32),
          np.squeeze(scores),
          category_index,
          use_normalized_coordinates=True,
          line_thickness=8)
      plt.figure(figsize=IMAGE_SIZE)
      plt.imshow(image_np)  
      '''

      # CWH: Print the object details to the console instead of visualizing them with the code above

      classes = np.squeeze(classes).astype(np.int32)
      scores = np.squeeze(scores)
      boxes = np.squeeze(boxes)
      # print(scores)
      threshold = 0.20  # CWH: set a minimum score threshold of 50%
      obj_above_thresh = sum(n > threshold for n in scores)

      print("detected %s objects in %s above a %s score" %
            (obj_above_thresh, image_path, threshold))
      for c in range(0, len(classes)):
        if scores[c] > threshold:
          class_name = category_index[classes[c]]['name']
          print(" object %s is a %s - score: %s, location: %s" %
                (c, class_name, scores[c], boxes[c]))

この時間の経過を要約すると、このような行為は、実際にアルゴリズムを訓練アプリケーションの構成プログラム実行環境での難易度が非常に明白ではありません。だから私は、ブログの内容で、後でそれを行います。Googleの物体検出APIである-また、私も学習の珍しいソースへの道を見つけるために、この機会に起因します。まず、それはまた、唯一のネットワーク用の設定ファイルを変更することによって、MLの毛皮と接触するトレーニングの人々のために便利なことができ、高度に標準化への適応の作品に基づいています。我々の計算上のコンピューティングGoogleのクラウドで強調されているように、さらにはまた、クラウド上に配置することができ、このプロセスは、視覚的である、と私たちの焦点は、システム・レベル、さらにはハードウェアの問題に少なくなります、より多くのアルゴリズム上のコアの問題を議論することです。
さて、この練習の内容は終わりに来て、あなたがコメントで私を見つけることができるの問題がああセクションがあります〜

おすすめ

転載: www.cnblogs.com/gabriel-sun/p/12128406.html