在Windows下使用Tensorflow Object Detection API

Tensorflow Object Detection API是Tensorflow官方發(fā)布的一個(gè)建立在TensorFlow之上的開源框架,可以輕松構(gòu)建匹层,訓(xùn)練和部署對(duì)象檢測(cè)模型。TensorFlow官方使用TensorFlow Slim項(xiàng)目框?qū)崿F(xiàn)了近年來提出的多種優(yōu)秀的深度卷積神經(jīng)網(wǎng)絡(luò)框架仲器。

Tensorflow Object Detection API可以選擇的模型:

  • Single Shot Multibox Detector (SSD) with MobileNet,
  • SSD with Inception V2,
  • Region-Based Fully Convolutional Networks (R-FCN) with Resnet 101,
  • Faster RCNN with Resnet 101,
  • Faster RCNN with Inception Resnet v2

Githubhttps://github.com/tensorflow/models/tree/master/object_detection

在本文中蝶糯,我們實(shí)現(xiàn)了在Windows環(huán)境下運(yùn)行該框架的流程。在此之前我們要使用相關(guān)的卷積模型识虚,需要自行編譯作者指定的Caffe担锤,不同的框架使用的Caffe版本也不盡相同肛循。而基于其他深度學(xué)習(xí)框架的代碼受制于作者水平的不同银择,可用性與效率也不盡相同夹孔,因此TOD API在Tensorflow上提供了了一套標(biāo)準(zhǔn)化的編寫模式,既有利于使用怜俐,也有為編寫其他模型提供了例子佑菩。

環(huán)境

  • Windows 10
  • Python 3.6
  • Tensorflow-gpu 1.2
  • CUDA Toolkit 8與 cuDNN v5

首先我們安裝Tensorflow殿漠,最新的版本為1.2。在python 3.5+使用Tensorflow非常的簡(jiǎn)單蕾哟,不需要過多的流程莲蜘,只需要使用pip進(jìn)行安裝逐哈,所有相關(guān)的依賴就會(huì)自動(dòng)安裝完成问顷。

# For CPU
pip install tensorflow
# For GPU
pip install tensorflow-gpu

其次官方要求下列包,我們一同使用pip進(jìn)行安裝杜窄。

pip install pillow
pip install lxml
pip install jupyter
pip install matplotlib

Tensorflow Object Detection API使用Protobufs來配置模型和訓(xùn)練參數(shù)蚀腿。 在使用框架之前莉钙,必須編譯Protobuf庫胆胰。對(duì)于protobuf蜀涨,在Linux下我們可以使用apt-get安裝厚柳,在Windows下我們可以直接下載已經(jīng)編譯好的版本别垮,這里我們選擇下載列表中的protoc-3.3.0-win32.zip碳想。

Githubhttps://github.com/google/protobuf/releases

我們將bin文件夾加入到環(huán)境變量中胧奔,然后在CMD執(zhí)行protco命令胳泉,可以看到protobuf要求輸入文件岩遗。

protoc.jpg

接下來我們切換到models目錄下案铺,使用protoc命令編譯.proto文件

# From tensorflow/models/
protoc object_detection/protos/*.proto --python_out=.

我們可以看見.proto文件已經(jīng)被編譯為了.py文件红且。

proto.jpg

官方提供了一個(gè)object_detection_tutorial.ipynb文件,這個(gè)Demo會(huì)自動(dòng)下載并執(zhí)行最小最快的模型Single Shot Multibox Detector (SSD) with MobileNet涤姊。檢測(cè)結(jié)果如下:

1.png
2.png

為了方便在項(xiàng)目中使用,我們重寫了一個(gè)Python文件嗤放,其中網(wǎng)絡(luò)模型可以從下面的地址下載思喊,每一個(gè)模型都有一個(gè)frozen_inference_graph.pb文件。代碼與運(yùn)行結(jié)果如下:

Tensorflow detection model:
https://github.com/tensorflow/models/blob/master/object_detection/g3doc/detection_model_zoo.md

# coding:utf8
import os
import sys
import cv2
import numpy as np
import tensorflow as tf
sys.path.append("..")

from utils import label_map_util
from utils import visualization_utils as vis_util


class TOD(object):
    def __init__(self):
        # Path to frozen detection graph. This is the actual model that is used for the object detection.
        self.PATH_TO_CKPT = 'frozen_inference_graph.pb'

        # List of the strings that is used to add correct label for each box.
        self.PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')

        self.NUM_CLASSES = 90

        self.detection_graph = self._load_model()
        self.category_index = self._load_label_map()

    def _load_model(self):
        detection_graph = tf.Graph()
        with detection_graph.as_default():
            od_graph_def = tf.GraphDef()
            with tf.gfile.GFile(self.PATH_TO_CKPT, 'rb') as fid:
                serialized_graph = fid.read()
                od_graph_def.ParseFromString(serialized_graph)
                tf.import_graph_def(od_graph_def, name='')
        return detection_graph

    def _load_label_map(self):
        label_map = label_map_util.load_labelmap(self.PATH_TO_LABELS)
        categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=self.NUM_CLASSES, use_display_name=True)
        category_index = label_map_util.create_category_index(categories)
        return category_index

    def detect(self, image):
        with self.detection_graph.as_default():
            with tf.Session(graph=self.detection_graph) as sess:
                # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
                image_np_expanded = np.expand_dims(image, axis=0)
                image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')
                # Each box represents a part of the image where a particular object was detected.
                boxes = self.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.
                scores = self.detection_graph.get_tensor_by_name('detection_scores:0')
                classes = self.detection_graph.get_tensor_by_name('detection_classes:0')
                num_detections = self.detection_graph.get_tensor_by_name('num_detections:0')
                # Actual detection.
                (boxes, scores, classes, num_detections) = sess.run(
                    [boxes, scores, classes, num_detections],
                    feed_dict={image_tensor: image_np_expanded})
                # Visualization of the results of a detection.
                vis_util.visualize_boxes_and_labels_on_image_array(
                    image,
                    np.squeeze(boxes),
                    np.squeeze(classes).astype(np.int32),
                    np.squeeze(scores),
                    self.category_index,
                    use_normalized_coordinates=True,
                    line_thickness=8)

        while True:
            cv2.namedWindow("detection", cv2.WINDOW_NORMAL)
            cv2.imshow("detection", image)
            if cv2.waitKey(110) & 0xff == 27:
                break


if __name__ == '__main__':
    image = cv2.imread('dog.jpg')
    detecotr = TOD()
    detecotr.detect(image)

test.jpg
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末次酌,一起剝皮案震驚了整個(gè)濱河市恨课,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌岳服,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,265評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件拖吼,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡怠硼,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,078評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門同云,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人禁偎,你說我怎么就攤上這事盒至。” “怎么了?”我有些...
    開封第一講書人閱讀 156,852評(píng)論 0 347
  • 文/不壞的土叔 我叫張陵雹锣,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我证薇,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,408評(píng)論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上无午,老公的妹妹穿的比我還像新娘次泽。我一直安慰自己拳昌,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,445評(píng)論 5 384
  • 文/花漫 我一把揭開白布羹膳。 她就那樣靜靜地躺著醒颖,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上涕滋,一...
    開封第一講書人閱讀 49,772評(píng)論 1 290
  • 那天隘谣,我揣著相機(jī)與錄音党涕,去河邊找鬼噪珊。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的嫩舟。 我是一名探鬼主播饭于,決...
    沈念sama閱讀 38,921評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼钳榨,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼蝙搔!你這毒婦竟也來了镜硕?” 一聲冷哼從身側(cè)響起悠夯,我...
    開封第一講書人閱讀 37,688評(píng)論 0 266
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后瞬场,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,130評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡宵凌,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,467評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片始锚。...
    茶點(diǎn)故事閱讀 38,617評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡头谜,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出涵妥,到底是詐尸還是另有隱情蓬网,我是刑警寧澤窟坐,帶...
    沈念sama閱讀 34,276評(píng)論 4 329
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏评凝。R本人自食惡果不足惜篡诽,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,882評(píng)論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望榴捡。 院中可真熱鬧杈女,春花似錦、人聲如沸吊圾。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,740評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽项乒。三九已至啰劲,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間檀何,已是汗流浹背蝇裤。 一陣腳步聲響...
    開封第一講書人閱讀 31,967評(píng)論 1 265
  • 我被黑心中介騙來泰國(guó)打工廷支, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人栓辜。 一個(gè)月前我還...
    沈念sama閱讀 46,315評(píng)論 2 360
  • 正文 我出身青樓恋拍,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親藕甩。 傳聞我的和親對(duì)象是個(gè)殘疾皇子施敢,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,486評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容

  • 1. 介紹 首先讓我們來看看TensorFlow! 但是在我們開始之前狭莱,我們先來看看Python API中的Ten...
    JasonJe閱讀 11,725評(píng)論 1 32
  • 是一束光僵娃,是一眼清泉 從小長(zhǎng)出的想象 沒打預(yù)防針的童年 所以有那么多的疫情泛濫 我沒有美麗的故事可記憶 只有寂靜的...
    離夕閱讀 305評(píng)論 0 0
  • 對(duì)于Objective-C來說 Unit Testing的價(jià)值是什么默怨? 最大的問題是“對(duì)于Objective-C來...
    NSLogHome閱讀 360評(píng)論 0 0
  • 文/觀復(fù)知常 圖/來源網(wǎng)絡(luò) 過年在家,因外甥骤素、外甥女看動(dòng)畫片先壕,有幸又跟著看了幾集西游記,發(fā)現(xiàn)每當(dāng)唐僧師徒到一個(gè)...
    觀復(fù)知常閱讀 519評(píng)論 3 1