偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

入門指南:用Python實現(xiàn)實時目標(biāo)檢測(內(nèi)附代碼)

開發(fā) 后端
現(xiàn)在的CV工具能夠輕松地將目標(biāo)檢測應(yīng)用于圖片甚至是直播視頻。本文將簡單地展示如何用TensorFlow創(chuàng)建實時目標(biāo)檢測器。

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

這一特殊領(lǐng)域被稱為計算機(jī)視覺 (Computer Vision, CV),在現(xiàn)代生活中有著廣泛的應(yīng)用。

[[317857]]

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

現(xiàn)在的CV工具能夠輕松地將目標(biāo)檢測應(yīng)用于圖片甚至是直播視頻。本文將簡單地展示如何用TensorFlow創(chuàng)建實時目標(biāo)檢測器。

建立一個簡單的目標(biāo)檢測器

1. 設(shè)置要求:

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

一切就緒,現(xiàn)在開始吧!

2. 設(shè)置環(huán)境

第一步:從Github上下載或復(fù)制TensorFlow目標(biāo)檢測的代碼到本地計算機(jī)

在終端運(yùn)行如下命令:

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

第二步:安裝依賴項

下一步是確定計算機(jī)上配備了運(yùn)行目標(biāo)檢測器所需的庫和組件。

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

  • Cython
  • contextlib2
  • pillow
  • lxml
  • matplotlib

若有遺漏的組件,在運(yùn)行環(huán)境中執(zhí)行pip install即可。

第三步:安裝Protobuf編譯器

谷歌的Protobuf,又稱Protocol buffers,是一種語言無關(guān)、平臺無關(guān)、可擴(kuò)展的序列化結(jié)構(gòu)數(shù)據(jù)的機(jī)制。Protobuf幫助程序員定義數(shù)據(jù)結(jié)構(gòu),輕松地在各種數(shù)據(jù)流中使用各種語言進(jìn)行編寫和讀取結(jié)構(gòu)數(shù)據(jù)。

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

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

  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 

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

[[317858]]

來源:Pexels

第四步:編輯Protobuf編譯器

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

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

用Python實現(xiàn)目標(biāo)檢測

現(xiàn)在所有的依賴項都已經(jīng)安裝完畢,可以用Python實現(xiàn)目標(biāo)檢測了。

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

  1. models/research/object_detection 

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

  1. ssd_mobilenet_v1_coco_2017_11_17 

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

入門指南:用Python實現(xiàn)實時目標(biāo)檢測(內(nèi)附代碼)

要檢測直播視頻中的目標(biāo)還需要一些微調(diào)。在同一文件夾中新建一個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() 

在運(yùn)行Jupyter notebook時,網(wǎng)絡(luò)攝影系統(tǒng)會開啟并檢測所有原始模型訓(xùn)練過的物品類別。

責(zé)任編輯:趙寧寧 來源: 讀芯術(shù)
相關(guān)推薦

2017-09-22 11:45:10

深度學(xué)習(xí)OpenCVPython

2018-12-29 09:38:16

Python人臉檢測

2024-11-20 16:51:00

目標(biāo)檢測模型

2020-07-25 19:40:33

Java開發(fā)代碼

2024-06-21 10:40:00

計算機(jī)視覺

2019-08-01 12:47:26

目標(biāo)檢測計算機(jī)視覺CV

2020-06-10 21:56:53

醫(yī)療物聯(lián)網(wǎng)IOT

2023-11-17 09:35:58

2012-12-25 09:36:11

Storm大數(shù)據(jù)分析

2013-04-12 10:05:49

HTML5WebSocket

2016-04-21 11:50:33

虛擬現(xiàn)實

2020-08-25 18:10:22

Python代碼線性回歸

2024-06-18 10:20:00

YOLO目標(biāo)檢測

2024-07-24 10:12:47

2015-06-16 16:49:25

AWSKinesis實時數(shù)據(jù)處理

2022-12-06 15:59:14

人工智能

2024-05-17 08:07:46

Spring廣告推薦系統(tǒng)

2011-07-27 11:19:33

iPhone UITableVie

2018-01-23 09:17:22

Python人臉識別

2024-09-02 09:31:19

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號