入門指南:用Python實現實時目標檢測(內附代碼)

2020-12-14 讀芯術

全文共6821字,預計學習時長20分鐘

來源:Pexels

從自動駕駛汽車檢測路上的物體,到通過複雜的面部及身體語言識別發現可能的犯罪活動。多年來,研究人員一直在探索讓機器通過視覺識別物體的可能性。

這一特殊領域被稱為計算機視覺 (Computer Vision, CV),在現代生活中有著廣泛的應用。

目標檢測 (ObjectDetection) 也是計算機視覺最酷的應用之一,這是不容置疑的事實。

現在的CV工具能夠輕鬆地將目標檢測應用於圖片甚至是直播視頻。本文將簡單地展示如何用TensorFlow創建實時目標檢測器。

建立一個簡單的目標檢測器

設置要求:

TensorFlow版本在1.15.0或以上

執行pip install TensorFlow安裝最新版本

一切就緒,現在開始吧!

設置環境

第一步:從Github上下載或複製TensorFlow目標檢測的代碼到本地計算機

在終端運行如下命令:

git clonehttps://github.com/tensorflow/models.git

第二步:安裝依賴項

下一步是確定計算機上配備了運行目標檢測器所需的庫和組件。

下面列舉了本項目所依賴的庫。(大部分依賴都是TensorFlow自帶的)

· Cython

· contextlib2

· pillow

· lxml

· matplotlib

若有遺漏的組件,在運行環境中執行pip install即可。

第三步:安裝Protobuf編譯器

谷歌的Protobuf,又稱Protocol buffers,是一種語言無關、平臺無關、可擴展的序列化結構數據的機制。Protobuf幫助程式設計師定義數據結構,輕鬆地在各種數據流中使用各種語言進行編寫和讀取結構數據。

Protobuf也是本項目的依賴之一。點擊這裡了解更多關於Protobufs的知識。接下來把Protobuf安裝到計算機上。

打開終端或者打開命令提示符,將地址改為複製的代碼倉庫,在終端執行如下命令:

cd models/research \wget -Oprotobuf.zip https://github.com/protocolbuffers/protobuf/releases/download/v3.9.1/protoc-3.9.1-osx-x86_64.zip\unzipprotobuf.zip

注意:請務必在models/research目錄解壓protobuf.zip文件。

第四步:編輯Protobuf編譯器

從research/ directory目錄中執行如下命令編輯Protobuf編譯器:

./bin/protoc object_detection/protos/*.proto--python_out=.

用Python實現目標檢測

現在所有的依賴項都已經安裝完畢,可以用Python實現目標檢測了。

在下載的代碼倉庫中,將目錄更改為:

models/research/object_detection

這個目錄下有一個叫object_detection_tutorial.ipynb的ipython notebook。該文件是演示目標檢測算法的demo,在執行時會用到指定的模型:

ssd_mobilenet_v1_coco_2017_11_17

這一測試會識別代碼庫中提供的兩張測試圖片。下面是測試結果之一:

要檢測直播視頻中的目標還需要一些微調。在同一文件夾中新建一個Jupyter notebook,按照下面的代碼操作:

[1]:

import numpy as npimport osimport six.moves.urllib as urllibimport sysimport tarfileimport tensorflow as tfimport zipfilefrom distutils.version import StrictVersionfrom collections import defaultdictfrom io import StringIOfrom matplotlib import pyplot as pltfrom PIL import Image# This isneeded since the notebook is stored in the object_detection folder.sys.path.append("..")from utils import ops as utils_opsif StrictVersion(tf.__version__) < StrictVersion('1.12.0'): raise ImportError('Please upgrade your TensorFlow installation to v1.12.*.')

[2]:

# This isneeded to display the images.get_ipython().run_line_magic('matplotlib', 'inline')

[3]:

# Objectdetection imports# Here arethe imports from the object detection module.from utils import label_map_utilfrom utils import visualization_utils as vis_util

[4]:

# Modelpreparation# Anymodel exported using the `export_inference_graph.py` tool can be loaded heresimply by changing `PATH_TO_FROZEN_GRAPH` to point to a new .pb file.# Bydefault we use an "SSD with Mobilenet" model here.#See https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md#for alist of other models that can be run out-of-the-box with varying speeds andaccuracies.# Whatmodel 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 tofrozen detection graph. This is the actual model that is used for the objectdetection.PATH_TO_FROZEN_GRAPH= MODEL_NAME + '/frozen_inference_graph.pb'# List ofthe strings that is used to add correct label for each box.PATH_TO_LABELS= os.path.join('data', 'mscoco_label_map.pbtxt')

[5]:

#DownloadModelopener =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())

[6]:

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

[7]:

# Loadinglabel map# Labelmaps map indices to category names, so that when our convolution networkpredicts `5`,#we knowthat this corresponds to `airplane`. Here we use internal utilityfunctions,#butanything that returns a dictionary mapping integers to appropriate stringlabels would be finecategory_index= label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS,use_display_name=True)

[8]:

defrun_inference_for_single_image(image, graph): with graph.as_default(): with tf.Session() as sess: # Get handles to input and output tensors ops= tf.get_default_graph().get_operations() all_tensor_names= {output.name for op in ops for output in op.outputs} tensor_dict= {} for key in [ 'num_detections', 'detection_boxes', 'detection_scores', 'detection_classes', 'detection_masks']: tensor_name= key + ':0' if tensor_name in all_tensor_names: tensor_dict[key]= tf.get_default_graph().get_tensor_by_name(tensor_name) if'detection_masks'in tensor_dict: # The following processing is only for single image detection_boxes= tf.squeeze(tensor_dict['detection_boxes'], [0]) detection_masks= tf.squeeze(tensor_dict['detection_masks'], [0]) # Reframe is required to translate mask from boxcoordinates to image coordinates and fit the image size. real_num_detection= tf.cast(tensor_dict['num_detections'][0], tf.int32) detection_boxes= tf.slice(detection_boxes, [0, 0], [real_num_detection, -1]) detection_masks= tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1]) detection_masks_reframed= utils_ops.reframe_box_masks_to_image_masks( detection_masks,detection_boxes, image.shape[1],image.shape[2]) detection_masks_reframed= tf.cast( tf.greater(detection_masks_reframed,0.5),tf.uint8) # Follow the convention by adding back the batchdimension tensor_dict['detection_masks'] =tf.expand_dims( detection_masks_reframed,0) image_tensor= tf.get_default_graph().get_tensor_by_name('image_tensor:0') # Run inference output_dict= sess.run(tensor_dict, feed_dict={image_tensor: image}) # all outputs are float32 numpy arrays, so convert typesas appropriate output_dict['num_detections'] =int(output_dict['num_detections'][0]) output_dict['detection_classes'] =output_dict[ 'detection_classes'][0].astype(np.int64) output_dict['detection_boxes'] =output_dict['detection_boxes'][0] output_dict['detection_scores'] =output_dict['detection_scores'][0] if'detection_masks'in output_dict: output_dict['detection_masks'] =output_dict['detection_masks'][0] return output_dict

[9]:

import cv2cam =cv2.cv2.VideoCapture(0)rolling = Truewhile (rolling): ret,image_np = cam.read() image_np_expanded= np.expand_dims(image_np, axis=0) # Actual detection. output_dict= run_inference_for_single_image(image_np_expanded, detection_graph) # Visualization of the results of a detection. vis_util.visualize_boxes_and_labels_on_image_array( image_np, output_dict['detection_boxes'], output_dict['detection_classes'], output_dict['detection_scores'], category_index, instance_masks=output_dict.get('detection_masks'), use_normalized_coordinates=True, line_thickness=8) cv2.imshow('image', cv2.resize(image_np,(1000,800))) if cv2.waitKey(25) & 0xFF == ord('q'): break cv2.destroyAllWindows() cam.release()

在運行Jupyter notebook時,網絡攝影系統會開啟並檢測所有原始模型訓練過的物品類別。

感謝閱讀本文,如果有什麼建議,歡迎在留言區積極發言喲~

留言點讚關注

我們一起分享AI學習與發展的乾貨

如轉載,請後臺留言,遵守轉載規範

相關焦點

  • 從零開始實現穿衣圖像分割完整教程(附python代碼演練)
    它輸入原始的圖像(從網絡上下載或用智慧型手機拍照),並提取圖像中的連衣裙。 分割的難點在於原始圖像中存在了大量的噪聲,但是我們會在預處理期間通過一個技巧來解決這個問題。最後,您還可以嘗試將此解決方案與之前引用的解決方案合併。 這允許您通過外出和拍攝時拍攝的照片,開發一個實時推薦和標記服裝的系統。
  • 目標檢測必須要OpenCV?10行Python代碼也能實現,親測好用!
    大數據文摘出品編譯:朱一輝、雪清、小魚短短10行代碼就可以實現目標檢測?!本文作者和他的團隊構建了一個名為ImageAI 的Python庫,集成了現今流行的深度學習框架和計算機視覺庫。本文將手把手教你構建自己的第一個目標檢測應用,而且文摘菌已經幫你踩過坑了,親測有效!
  • 如何利用樹莓派實現基於深度學習的目標檢測(入門)
    儘管只有信用卡大小,但視頻、音頻等功能都可以實現,可謂是「麻雀雖小,五臟俱全」。今天將通過工作室陳成琳學姐的實驗,從實驗目的、實驗步驟、實驗總結為大家介紹如何利用樹莓派實現基於深度學習的目標檢測。系統默認自帶2.x版本和3.x版本,你可以用命令:python –V 查看默認python版本python3 –V 查看python3.x的版本。如果有的系統沒有自帶3.x版本,需要自行安裝。
  • 基於TensorFlow 、OpenCV 和 Docker 的實時視頻目標檢測
    我將使用 python 的 multiprocessing 庫,增加處理網絡攝像頭時的 FPS。為了進一步提高可移植性,我將項目集成到 Docker 容器中。不過處理進出容器的視頻流可能會有一點麻煩。此外,在次項目我還添加了一個視頻後處理功能,同樣使用 multiprocessing 庫來減少處理時間(使用 Tensorflow 原始目標檢測 API 處理時間會非常長)。
  • 分享《深度學習入門:基於Python的理論與實現》高清中文版PDF+原始碼
    《深度學習入門:基於Python的理論與實現》本書是深度學習真正意義上的入門書,深入淺出地剖析了深度學習的原理和相關技術。書中使用Python3,儘量不依賴外部庫或工具,從基本的數學知識出發,帶領讀者從零創建一個經典的深度學習網絡,使讀者在此過程中逐步理解深度學習。
  • 增加檢測類別?這是一份目標檢測的一般指南
    本文是目標檢測的一般指南,它並沒有詳細介紹主流的目標檢測算法,這些算法讀者可參考從 RCNN 到 SSD,這應該是最全的一份目標檢測算法盤點。我儘可能對深度學習目標檢測器的組成做一個概述,包括使用預訓練的目標檢測器執行任務的原始碼。你可以使用這份指南來幫助學習深度學習目標檢測,但是也要意識到,目標檢測是高度細節化的工作,我不可能在一篇文章中包含關於深度學習目標檢測的所有細節。
  • Stacking 模型融合詳解(附python代碼)
    那麼同樣,對於測試集第一層出來的維度是不是(test_set_number,n),也就是測試集樣本的行數,這樣是不是可以用第二層訓練的模型在這個上面預測,得到我們最後的結果。這個就是stacking的整個過程。然後我們看一段stacking的代碼:
  • 入門Python, 看這些資料就夠了
    要入門Python,資料並非越多越好, 基本上看這些資料就夠了。 。目錄:第一部分: Python入門&進階教程第二部分: Python Web框架第三部分: Python擴展資料推薦的學習路徑: 1. 使用實驗樓的開箱即用環境快速刷完Python3簡明教程,django基礎教程;2.
  • OpenCV+Tensorflow實現實時人臉識別演示
    FaceNet網絡設計目標任務有如下1.驗證-驗證是否為同一張臉2.識別-識別是否為同一個人3.聚類-發現人臉具有相同之處的人關於什麼是神經網絡嵌入,這個解釋比較複雜,簡單的說神經網絡的嵌入學習可以幫助我們把離散變量表示為連續的向量,在低維空間找到最近鄰,tensorflow中的word2vec就是用了嵌入。
  • 針對 Quant 的 Python 快速入門指南
    作者:用Python的交易員最近有越來越多的朋友在知乎或者QQ上問我如何學習入門Python,就目前需求來看,我需要寫這麼一篇指南
  • 如何基於Flutter和Paddle Lite實現實時目標檢測
    很早之前接觸到了飛槳(PaddlePaddle)以及PaddleDetection工具,被他們的簡單易用吸引,同時,這些工具極大降低了訓練模型的門檻並減少了所需時間,非常適合新手入門。在很多實際應用場景也有不俗的表現。
  • Python網絡編程入門
    Python 網絡編程入門:套接字(Socket)通信簡介聲明:本編推送前半部分內容翻譯自: https://realpython.com
  • Python不超過10行代碼就可實現人臉識別,教你辨別真假
    這裡沒有用PIL,再結合特定算法,而是直接使用了OpenCV(http://opencv.org)。OpenCV是一個基於BSD許可發行的跨平臺計算機視覺庫,可以運行在Linux、Windows和Mac OS作業系統上,輕量而且高效,用C/C++編寫,同時提供了Python、Ruby、MATLAB等接口,實現了圖像處理和計算機視覺方面的很多通用算法。
  • 出國必備,用python實現美元和人民幣的實時匯率兌換
    各個國家的流通貨幣是不同的,而當我們要出國時,就需要先算好貨幣之間的兌換,而羽憶教程下面為你介紹用python實現美元和人民幣之間的實時匯率兌換。,但是為了方便快捷,小編將為您設計一個人民幣和元元實時匯率兌換的python程序,節省用戶時間。
  • Python冬令營-網絡編程入門
    Python 網絡編程入門:套接字(Socket)通信簡介聲明:本編推送前半部分內容翻譯自: https://realpython.com
  • 中文文本錯別字檢測以及自動糾錯
    做表格檢測《基於深度學習的自然語言處理》中/英PDFDeep Learning 中文版初版-周志華團隊【全套視頻課】最全的目標檢測算法系列講解,通俗易懂!《美團機器學習實踐》_美團算法團隊.pdf《深度學習入門:基於Python的理論與實現》高清中文PDF+源碼特徵提取與圖像處理(第二版).pdfpython就業班學習視頻,從入門到實戰項目2019最新《PyTorch
  • 十六本python入門學習書籍推薦,python入門新手必看
    隨著人工智慧時代的到來,python程式語言一步登天衝到編程排行榜第一名,因此更多朋友想轉行學習python程式語言的朋友,可以一起看一下:python入門新手必看的十六本python入門學習書籍1、python基礎教程司維所著圖書:本書包括Python程序設計的方方面面,首先從Python
  • 深度學習目標檢測系列:faster RCNN實現|附python源碼
    目標檢測一直是計算機視覺中比較熱門的研究領域,有一些常用且成熟的算法得到業內公認水平,比如RCNN系列算法、SSD以及YOLO等。如果你是從事這一行業的話,你會使用哪種算法進行目標檢測任務呢?在我尋求在最短的時間內構建最精確的模型時,我嘗試了其中的R-CNN系列算法,如果讀者們對這方面的算法還不太了解的話,建議閱讀《目標檢測算法圖解:一文看懂RCNN系列算法》。
  • CVPR 2020文本圖像檢測與識別論文/代碼
    Making Better Mistakes: Leveraging Class Hierarchies with Deep Networks論文:Making Better Mistakes: Leveraging Class Hierarchies with Deep Networks# 目標檢測和分割!
  • 手把手教你使用樹莓派實現實時人臉檢測
    語言和庫:步驟本文主要講述如何使用 PiCam 實現實時人臉識別,如下圖所示:本教程使用 OpenCV 完成,一個神奇的「開源計算機視覺庫」,並主要關注樹莓派(因此,作業系統是樹莓派系統)和 Python,但是我也在 Mac 電腦上測試了代碼,同樣運行很好。