成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

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

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

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

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

[[317857]]

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

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

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

1. 設置要求:

  • TensorFlow版本在1.15.0或以上
  • 執行pip install TensorFlow安裝最新版本

一切就緒,現在開始吧!

2. 設置環境

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

在終端運行如下命令:

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

第二步:安裝依賴項

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

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

  • Cython
  • contextlib2
  • pillow
  • lxml
  • matplotlib

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

第三步:安裝Protobuf編譯器

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

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

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

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

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

[[317858]]

來源:Pexels

第四步:編輯Protobuf編譯器

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

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

用Python實現目標檢測

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

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

  1. models/research/object_detection 

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

  1. ssd_mobilenet_v1_coco_2017_11_17 

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

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

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

[1]:

  1. import numpy as np 
  2. import os 
  3. import six.moves.urllib as urllib 
  4. import sys 
  5. import tarfile 
  6. import tensorflow as tf 
  7. import zipfile 
  8. from distutils.version import StrictVersion 
  9. from collections import defaultdict 
  10. from io import StringIO 
  11. from matplotlib import pyplot as plt 
  12. from PIL import Image 
  13. # This isneeded since the notebook is stored in the object_detection folder. 
  14. sys.path.append("..") 
  15. from utils import ops as utils_ops 
  16. if StrictVersion(tf.__version__) < StrictVersion( 1.12.0 ): 
  17.     raise ImportError( Please upgrade your TensorFlow installation to v1.12.*. ) 

[2]:

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

[3]:

  1. # Objectdetection imports 
  2. # Here arethe imports from the object detection module. 
  3. from utils import label_map_util 
  4. from utils import visualization_utils as vis_util 

[4]:

  1. # Modelpreparation  
  2. # 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. 
  3. # Bydefault we use an "SSD with Mobilenet" model here.  
  4. #See https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md 
  5. #for alist of other models that can be run out-of-the-box with varying speeds andaccuracies. 
  6. # Whatmodel to download. 
  7. MODEL_NAME=  ssd_mobilenet_v1_coco_2017_11_17  
  8. MODEL_FILEMODEL_NAME +  .tar.gz  
  9. DOWNLOAD_BASE=  http://download.tensorflow.org/models/object_detection/  
  10. # Path tofrozen detection graph. This is the actual model that is used for the objectdetection. 
  11. PATH_TO_FROZEN_GRAPHMODEL_NAME +  /frozen_inference_graph.pb  
  12. # List ofthe strings that is used to add correct label for each box. 
  13. PATH_TO_LABELSos.path.join( data ,  mscoco_label_map.pbtxt ) 

[5]:

  1. #DownloadModel 
  2. opener =urllib.request.URLopener() 
  3. opener.retrieve(DOWNLOAD_BASE+ MODEL_FILE, MODEL_FILE) 
  4. tar_file =tarfile.open(MODEL_FILE) 
  5. for file in tar_file.getmembers(): 
  6.     file_nameos.path.basename(file.name) 
  7.     if frozen_inference_graph.pb in file_name: 
  8.         tar_file.extract(file,os.getcwd()) 

[6]:

  1. # Load a(frozen) Tensorflow model into memory. 
  2. detection_graphtf.Graph() 
  3. with detection_graph.as_default(): 
  4.     od_graph_deftf.GraphDef() 
  5.     withtf.gfile.GFile(PATH_TO_FROZEN_GRAPH,  rb ) as fid: 
  6.         serialized_graphfid.read() 
  7.         od_graph_def.ParseFromString(serialized_graph) 
  8.         tf.import_graph_def(od_graph_def,name=  ) 

[7]:

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

[8]:

  1. defrun_inference_for_single_image(image, graph): 
  2.     with graph.as_default(): 
  3.         with tf.Session() as sess: 
  4.             # Get handles to input and output tensors 
  5.             opstf.get_default_graph().get_operations() 
  6.             all_tensor_names= {output.name for op in ops for output in op.outputs} 
  7.             tensor_dict= {} 
  8.             for key in [ 
  9.                    num_detections ,  detection_boxes ,  detection_scores , 
  10.                    detection_classes ,  detection_masks ]: 
  11.                 tensor_namekey +  :0  
  12.                 if tensor_name in all_tensor_names: 
  13.                     tensor_dict[key]= tf.get_default_graph().get_tensor_by_name(tensor_name) 
  14.             if detection_masks in tensor_dict: 
  15.                 # The following processing is only for single image 
  16.                 detection_boxestf.squeeze(tensor_dict[ detection_boxes ], [0]) 
  17.                 detection_maskstf.squeeze(tensor_dict[ detection_masks ], [0]) 
  18.                 # Reframe is required to translate mask from boxcoordinates to image coordinates and fit the image size. 
  19.                 real_num_detectiontf.cast(tensor_dict[ num_detections ][0], tf.int32) 
  20.                 detection_boxestf.slice(detection_boxes, [0, 0], [real_num_detection, -1]) 
  21.                 detection_maskstf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1]) 
  22.                 detection_masks_reframedutils_ops.reframe_box_masks_to_image_masks( 
  23.                 detection_masks,detection_boxes, image.shape[1],image.shape[2]) 
  24.                 detection_masks_reframedtf.cast( 
  25.                 tf.greater(detection_masks_reframed,0.5),tf.uint8) 
  26.                 # Follow the convention by adding back the batchdimension 
  27.                 tensor_dict[ detection_masks ] =tf.expand_dims( 
  28.                                     detection_masks_reframed,0) 
  29.             image_tensortf.get_default_graph().get_tensor_by_name( image_tensor:0 ) 
  30.             # Run inference 
  31.             output_dictsess.run(tensor_dict, feed_dict={image_tensor: image}) 
  32.             # all outputs are float32 numpy arrays, so convert typesas appropriate 
  33.             output_dict[ num_detections ] =int(output_dict[ num_detections ][0]) 
  34.             output_dict[ detection_classes ] =output_dict[ 
  35.                        detection_classes ][0].astype(np.int64) 
  36.             output_dict[ detection_boxes ] =output_dict[ detection_boxes ][0] 
  37.             output_dict[ detection_scores ] =output_dict[ detection_scores ][0] 
  38.             if detection_masks in output_dict: 
  39.                 output_dict[ detection_masks ] =output_dict[ detection_masks ][0] 
  40.         return output_dict 

[9]:

  1. import cv2 
  2. cam =cv2.cv2.VideoCapture(0) 
  3. rolling = True 
  4. while (rolling): 
  5.     ret,image_np = cam.read() 
  6.     image_np_expanded= np.expand_dims(image_np, axis=0
  7.     # Actual detection. 
  8.     output_dictrun_inference_for_single_image(image_np_expanded, detection_graph) 
  9.     # Visualization of the results of a detection. 
  10.     vis_util.visualize_boxes_and_labels_on_image_array( 
  11.       image_np, 
  12.       output_dict[ detection_boxes ], 
  13.       output_dict[ detection_classes ], 
  14.       output_dict[ detection_scores ], 
  15.       category_index, 
  16.       instance_masks=output_dict.get( detection_masks ), 
  17.       use_normalized_coordinates=True
  18.       line_thickness=8
  19.     cv2.imshow( image , cv2.resize(image_np,(1000,800))) 
  20.     if cv2.waitKey(25) & 0xFF == ord( q ): 
  21.         break 
  22.         cv2.destroyAllWindows() 
  23.         cam.release() 

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

責任編輯:趙寧寧 來源: 讀芯術
相關推薦

2017-09-22 11:45:10

深度學習OpenCVPython

2018-12-29 09:38:16

Python人臉檢測

2024-11-20 16:51:00

目標檢測模型

2020-07-25 19:40:33

Java開發代碼

2024-06-21 10:40:00

計算機視覺

2019-08-01 12:47:26

目標檢測計算機視覺CV

2016-04-21 11:50:33

虛擬現實

2020-06-10 21:56:53

醫療物聯網IOT

2012-12-25 09:36:11

Storm大數據分析

2013-04-12 10:05:49

HTML5WebSocket

2023-11-17 09:35:58

2022-12-06 15:59:14

人工智能

2015-06-16 16:49:25

AWSKinesis實時數據處理

2024-05-17 08:07:46

Spring廣告推薦系統

2024-09-02 09:31:19

2025-06-16 04:00:00

Spring彈幕技術

2024-06-18 10:20:00

YOLO目標檢測

2024-07-24 10:12:47

2011-07-27 11:19:33

iPhone UITableVie

2024-05-17 13:17:39

點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 亚洲婷婷六月天 | 免费视频一区 | 在线日韩欧美 | 亚洲一区二区免费看 | 精品一区二区三区在线观看国产 | 999热视频 | 成人在线视频看看 | 成人免费观看视频 | 日本在线看片 | 精品视频一区二区三区 | 中文字幕乱码一区二区三区 | 九九热九九 | 亚洲在线免费观看 | 综合久久99 | 91精品久久久久久久久久 | 97国产爽爽爽久久久 | 国产专区在线 | 在线免费黄色小视频 | 北条麻妃99精品青青久久主播 | 欧美一区二区三区大片 | 99视频网| 男人亚洲天堂 | 中文字幕成人在线 | 欧美精品一区二区三区一线天视频 | 成人精品久久 | 国产精品夜色一区二区三区 | 国产美女在线观看 | 亚洲精品一区二区 | 夜夜爽99久久国产综合精品女不卡 | 欧美激情va永久在线播放 | 一区二区国产精品 | 国产美女黄色片 | 黄色一级在线播放 | xx视频在线| 狠狠色香婷婷久久亚洲精品 | 久久伦理电影 | 精品久久久久久久人人人人传媒 | 欧美三区在线观看 | 日本不卡一区二区 | 狠狠入ady亚洲精品经典电影 | 欧美日韩专区 |