稱為計算機(jī)視覺或CV的特定領(lǐng)域具有廣泛的現(xiàn)代應(yīng)用程序。從被自動駕駛汽車用作道路目標(biāo)檢測到復(fù)雜的面部和肢體語言識別(可以識別可能的犯罪或犯罪活動),CV在當(dāng)今世界中有很多用途。不可否認(rèn),對象檢測還是Computer Vision最酷的應(yīng)用之一。當(dāng)今的CV工具可以輕松地在圖像甚至是實時流視頻上實現(xiàn)對象檢測。在此處,我們將看一下使用TensorFlow進(jìn)行實時對象檢測的簡單演示。
設(shè)置簡單的對象檢測器
先決條件:
Tensorflow> = 1.15.0
通過執(zhí)行pip install tensorflow安裝最新版本
營造環(huán)境
步驟1.下載或克隆TensorFlow對象檢測代碼到本地計算機(jī)中
在終端中執(zhí)行以下命令:git clone如果您的計算機(jī)上未安裝git,則可以選擇從此處下載zip文件。
步驟2.安裝依賴項
下一步是確保我們擁有在計算機(jī)上運行對象檢測器所需的所有庫和模塊。
?。ㄊ乔闆r下,大多數(shù)依賴項都隨隨Tensorflow一起提供)
·賽頓
·contextlib2
·枕頭
·xml文件
·matplotlib
如果您發(fā)現(xiàn)任何任何模塊,只需在您的環(huán)境中執(zhí)行pip install即可安裝。
步驟3.安裝Protobuf編譯器
Protobuf或Protocol示例是Google的語言無關(guān),平臺無關(guān)的可擴(kuò)展機(jī)制,用于序列化結(jié)構(gòu)化數(shù)據(jù)。它可以幫助我們定義我們希望數(shù)據(jù)的結(jié)構(gòu)方式,一旦結(jié)構(gòu)化,就可以輕松地使用各種語言在各種數(shù)據(jù)流之間讀寫結(jié)構(gòu)化數(shù)據(jù)。
這也是該項目的依賴項。您可以在此處了解有關(guān)Protobufs的更多信息?,F(xiàn)在,選擇適合您的操作系統(tǒng)的版本,然后復(fù)制下載鏈接。
?。航K端或命令向?qū)В瑢⒛夸浉臑榭寺〉拇鎯?,然后在終端中執(zhí)行以下命令。
cd模型/研究
wget -O protobuf.zip
解壓縮protobuf.zip
注意:請確保在模型/研究目錄中解壓縮protobuf.zip文件
步驟4.編譯Protobuf編譯器
從研究/目錄執(zhí)行以下命令以編譯協(xié)議捆綁。
在Python中實現(xiàn)對象檢測
現(xiàn)在,我們已經(jīng)安裝了所有依賴項,讓我們使用Python來實現(xiàn)對象檢測。
在此目錄中,您將找到一個名為object_detection_tutorial.ipynb的ipython筆記本。該文件是用于對象檢測的演示,執(zhí)行時將使用指定的“ ssd_mobilenet_v1_coco_2017_11_17模型對存儲庫中提供的兩個測試圖像進(jìn)行分類。
以下是測試輸出之一:
在相同的文件夾中制作一個新的Jupyter筆記本,并遵循以下代碼。
在[1]中:
import numpy as npimport osimport six.moves.urllib as urllibimport sysimport tarimport import tensorflow as tfimport zipfile from distutils.version import strictVersionfrom collections import defaultdictfrom io import matplotlib import pyplot as plt from PIL import Image#這是必需的,因為筆記本存儲在object_中。
utils中的sys.path.append(“ ..”)作為utils_opsif StrictVersion(tf .__ version__)<StrictVersion('1.12.0'):
提高ImportError('請將您的TensorFlow安裝升級到v1.12。*。')
在[2]中:
?。_@是顯示圖像所必需的。
get_ipython()。run_line_magic('matplotlib','inline')
在[3]中:
?。ο髾z測導(dǎo)入#這是來自對象檢測模塊的導(dǎo)入。from utils import label_map_utilfrom utils import visualization_utils as vis_util
在[4]中:
?。DP蜏?zhǔn)備#使用`export_inference_graph.py`工具導(dǎo)出的任何模型都可以通過更改`PATH_TO_FROZEN_GRAPH`指向新的.pb文件來加載。#默認(rèn)情況下,我們在此處使用“帶有Mobilenet的SSD”模型。#看到
MODEL_NAME ='ssd_mobilenet_v1_coco_2017_11_17'
MODEL_FILE = MODEL_NAME +'.tar.gz'
DOWNLOAD_BASE =#凍結(jié)檢測圖的路徑。這是用于對象檢測的實際模型。
PATH_TO_FROZEN_GRAPH = MODEL_NAME +'/frozen_inference_graph.pb'#用于為每個框添加正確標(biāo)簽的字符串列表。
PATH_TO_LABELS = os.path.join('data','mscoco_label_map.pbtxt')
在[5]中:
#下載模型
開瓶器= urllib.request.URLopener()
opener.retrieve(DOWNLOAD_BASE + MODEL_FILE,MODEL_FILE)
tar_file = tarfile.open(MODEL_FILE)用于tar_file.getmembers()中的文件:
file_name = os.path.basename(file.name)
如果文件名中的“ frozen_inference_graph.pb”:
tar_file.extract(文件,os.getcwd())
在[6]中:
#將一個(凍結(jié)的)Tensorflow模型加載到內(nèi)存中。
detection_graph = tf.Graph()和detection_graph.as_default():
od_graph_def = tf.GraphDef()
使用tf.gfile.GFile(PATH_TO_FROZEN_GRAPH,'rb')作為fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def,name ='')
在[7]中:
?。<虞d標(biāo)簽地圖#標(biāo)簽將地圖索引映射到類別名稱,這樣,當(dāng)我們的卷積網(wǎng)絡(luò)預(yù)測“ 5”時,#我們知道它對應(yīng)于“飛機(jī)”。在這里,我們使用內(nèi)部實用程序函數(shù),但是任何返回將整數(shù)映射到適當(dāng)?shù)淖址畼?biāo)簽的字典的方法都可以
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS,use_display_name = True)
在[8]中:
def run_inference_for_single_image(圖像,圖形):
與graph.as_default():
與tf.Session()作為sess:
#獲取輸入和輸出張量的句柄
ops = tf.get_default_graph()。get_operations()
all_tensor_names = {ops中op的output.name在op.outputs中的輸出}
tensor_dict = {}
用于輸入[
'num_detections','detection_boxes','detection_scores',
'detection_classes','detection_masks']:
張量名稱=鍵+':0'
如果tensor_name在all_tensor_names中:
tensor_dict [key] = tf.get_default_graph()。get_tensor_by_name(tensor_name)
如果tensor_dict中的'detection_masks':
?。R韵绿幚韮H適用于單個圖像
detection_boxes = tf.squeeze(tensor_dict ['detection_boxes'],[0])
detection_masks = tf.squeeze(tensor_dict ['detection_masks'],[0])
?。P枰匦驴蚣芤詫⒚砂鎻目蜃鴺?biāo)轉(zhuǎn)換為圖像坐標(biāo)并適合圖像尺寸。
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)
#遵循慣例,重新添加批次尺寸
tensor_dict ['detection_masks'] = tf.expand_dims(
detection_masks_reframed,0)
image_tensor = tf.get_default_graph()。get_tensor_by_name('image_tensor:0')
?。_\行推斷
output_dict = sess.run(tensor_dict,feed_dict = {image_tensor:image})
?。K休敵鼍鶠閒loat32 numpy數(shù)組,因此請適當(dāng)轉(zhuǎn)換類型
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]
如果output_dict中的“ detection_masks”:
output_dict ['detection_masks'] = output_dict ['detection_masks'] [0]
返回output_dict
在[8]中:
導(dǎo)入cv2
cam = cv2.cv2.VideoCapture(0)
滾動= Truewhile(滾動):
ret,image_np = cam.read()
image_np_expanded = np.expand_dims(image_np,axis = 0)
?。嶋H檢測。
output_dict = run_inference_for_single_image(image_np_expanded,detection_graph)
?。?梢暬瘷z測結(jié)果。
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 =是,
line_thickness = 8)
cv2.imshow('image',cv2.resize(image_np,(1000,800)))
如果cv2.waitKey(25)和0xFF == ord('q'):
打破
cv2.destroyAllWindows()
cam.release()
以上即是關(guān)于Python實時對象檢測入門指南的全部內(nèi)容,想了解更多更多關(guān)于Python的信息,請繼續(xù)關(guān)注中培偉業(yè)。