基于tensorflow的實(shí)時(shí)物體識(shí)別

google開(kāi)源了基于深度學(xué)習(xí)的物體識(shí)別模型和python API啤它。

  1. API結(jié)構(gòu)微調(diào)娃殖;
  2. 多線(xiàn)程值戳,讀取視頻流议谷;
  3. 多進(jìn)程炉爆,加載物體識(shí)別模型;

API結(jié)構(gòu)微調(diào)

import os
import cv2
import numpy as np
import multiprocessing
from multiprocessing import Queue, Pool

# tensorflow api 接口相關(guān)函數(shù)
import tensorflow as tf
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util

# 模型路徑
PATH_TO_CKPT = '../object_detection/ssd_mobilenet_v1_coco_11_06_2017/frozen_inference_graph.pb')

# label字典路徑卧晓,用于識(shí)別出物品后展示類(lèi)別名
PATH_TO_LABELS = '../object_detection/data/mscoco_label_map.pbtxt'
NUM_CLASSES = 90 # 最大分類(lèi)數(shù)量
label_map = label_map_util.load_labelmap(PATH_TO_LABELS) # 獲得類(lèi)別字典
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)

# 物體識(shí)別神經(jīng)網(wǎng)絡(luò)芬首,向前傳播獲得識(shí)別結(jié)果
def detect_objects(image_np, sess, detection_graph):
    # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
    image_np_expanded = np.expand_dims(image_np, axis=0)
    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.
    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.
    scores = detection_graph.get_tensor_by_name('detection_scores:0')
    classes = detection_graph.get_tensor_by_name('detection_classes:0')
    num_detections = 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,
        np.squeeze(boxes),
        np.squeeze(classes).astype(np.int32),
        np.squeeze(scores),
        category_index,
        use_normalized_coordinates=True,
        line_thickness=3)
    return image_np

多線(xiàn)程,讀取視頻流

更多資料參考 Increasing webcam FPS with Python and OpenCV

import cv2
from threading import Thread

# 多線(xiàn)程逼裆,高效讀視頻
class WebcamVideoStream:
    def __init__(self, src, width, height):
        # initialize the video camera stream and read the first frame
        # from the stream
        self.stream = cv2.VideoCapture(src)
        self.stream.set(cv2.CAP_PROP_FRAME_WIDTH, width)
        self.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
        (self.grabbed, self.frame) = self.stream.read()

        # initialize the variable used to indicate if the thread should
        # be stopped
        self.stopped = False

    def start(self):
        # start the thread to read frames from the video stream
        Thread(target=self.update, args=()).start()
        return self

    def update(self):
        # keep looping infinitely until the thread is stopped
        while True:
            # if the thread indicator variable is set, stop the thread
            if self.stopped:
                return

            # otherwise, read the next frame from the stream
            (self.grabbed, self.frame) = self.stream.read()

    def read(self):
        # return the frame most recently read
        return self.frame

    def stop(self):
        # indicate that the thread should be stopped
        self.stopped = True

# 使用方法
video_capture = WebcamVideoStream(src=video_source,
                                      width=width,
                                      height=height).start()
frame = video_capture.read()

多進(jìn)程郁稍,加載物體識(shí)別模型

  • 配置參數(shù)
     class configs(object):
         def __init__(self):
             self.num_workers = 2 # worker數(shù)量
             self.queue_size = 5  # 多進(jìn)程,輸入輸出胜宇,隊(duì)列長(zhǎng)度
             self.video_source = 0 # 0代表從攝像頭讀取視頻流
             self.width = 720 # 圖片寬
             self.height = 490 # 圖片高
     args = configs()
    
  • 定義用于多進(jìn)程執(zhí)行的函數(shù)word耀怜,每個(gè)進(jìn)程執(zhí)行work函數(shù),都會(huì)加載一次模型
    def worker(input_q, output_q):
        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='')
            sess = tf.Session(graph=detection_graph)
    
        while True: # 全局變量input_q與output_q定義桐愉,請(qǐng)看下文
            frame = input_q.get() # 從多進(jìn)程輸入隊(duì)列财破,取值
            output_q.put(detect_objects(frame, sess, detection_graph)) # detect_objects函數(shù) 返回一張圖片,標(biāo)記所有被發(fā)現(xiàn)的物品
        sess.close()
    
  • 多進(jìn)程 Queue 文檔 (Exchanging objects between processes)
    import multiprocessing
    input_q = Queue(maxsize=args.queue_size) # 多進(jìn)程輸入隊(duì)列
    output_q = Queue(maxsize=args.queue_size) # 多進(jìn)程輸出隊(duì)列
    pool = Pool(args.num_workers, worker, (input_q, output_q)) # 多進(jìn)程加載模型
    
    video_capture = WebcamVideoStream(src=args.video_source,
                                      width=args.width,
                                      height=args.height).start()
    
    while True: 
        frame = video_capture.read() # video_capture多線(xiàn)程讀取視頻流
        input_q.put(frame) # 視頻幀放入多進(jìn)程輸入隊(duì)列
        frame = output_q.get() # 多進(jìn)程輸出隊(duì)列取出標(biāo)記好物體的圖片
    
        cv2.imshow('Video', frame) # 展示已標(biāo)記物體的圖片
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    pool.terminate() # 關(guān)閉多進(jìn)程
    video_capture.stop() # 關(guān)閉視頻流
    cv2.destroyAllWindows() # opencv窗口關(guān)閉
    
簡(jiǎn)單測(cè)試
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末从诲,一起剝皮案震驚了整個(gè)濱河市左痢,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌系洛,老刑警劉巖俊性,帶你破解...
    沈念sama閱讀 221,635評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異描扯,居然都是意外死亡定页,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,543評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén)绽诚,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)典徊,“玉大人,你說(shuō)我怎么就攤上這事憔购」停” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 168,083評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵玫鸟,是天一觀(guān)的道長(zhǎng)导绷。 經(jīng)常有香客問(wèn)我,道長(zhǎng)屎飘,這世上最難降的妖魔是什么妥曲? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,640評(píng)論 1 296
  • 正文 為了忘掉前任贾费,我火速辦了婚禮,結(jié)果婚禮上檐盟,老公的妹妹穿的比我還像新娘褂萧。我一直安慰自己,他們只是感情好葵萎,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,640評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布导犹。 她就那樣靜靜地躺著,像睡著了一般羡忘。 火紅的嫁衣襯著肌膚如雪谎痢。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 52,262評(píng)論 1 308
  • 那天卷雕,我揣著相機(jī)與錄音节猿,去河邊找鬼。 笑死漫雕,一個(gè)胖子當(dāng)著我的面吹牛滨嘱,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播浸间,決...
    沈念sama閱讀 40,833評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼太雨,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了发框?” 一聲冷哼從身側(cè)響起躺彬,我...
    開(kāi)封第一講書(shū)人閱讀 39,736評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎梅惯,沒(méi)想到半個(gè)月后宪拥,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,280評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡铣减,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,369評(píng)論 3 340
  • 正文 我和宋清朗相戀三年她君,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片葫哗。...
    茶點(diǎn)故事閱讀 40,503評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡缔刹,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出劣针,到底是詐尸還是另有隱情校镐,我是刑警寧澤,帶...
    沈念sama閱讀 36,185評(píng)論 5 350
  • 正文 年R本政府宣布捺典,位于F島的核電站鸟廓,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜引谜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,870評(píng)論 3 333
  • 文/蒙蒙 一牍陌、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧员咽,春花似錦毒涧、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,340評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至档玻,卻和暖如春怀泊,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背误趴。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,460評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留务傲,地道東北人凉当。 一個(gè)月前我還...
    沈念sama閱讀 48,909評(píng)論 3 376
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像售葡,于是被迫代替她去往敵國(guó)和親看杭。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,512評(píng)論 2 359

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