亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術文章
文章詳情頁

OpenCV+python實現實時目標檢測功能

瀏覽:16日期:2022-07-19 15:25:25

環境安裝

安裝Anaconda,官網鏈接Anaconda 使用conda創建py3.6的虛擬環境,并激活使用

conda create -n py3.6 python=3.6 //創建conda activate py3.6 //激活

OpenCV+python實現實時目標檢測功能

3.安裝依賴numpy和imutils

//用鏡像安裝pip install -i https://pypi.tuna.tsinghua.edu.cn/simple numpypip install -i https://pypi.tuna.tsinghua.edu.cn/simple imutils

4.安裝opencv

(1)首先下載opencv(網址:opencv),在這里我選擇的是opencv_python‑4.1.2+contrib‑cp36‑cp36m‑win_amd64.whl 。(2)下載好后,把它放到任意盤中(這里我放的是D盤),切換到安裝目錄,執行安裝命令:pip install opencv_python‑4.1.2+contrib‑cp36‑cp36m‑win_amd64.whl

代碼

首先打開一個空文件命名為real_time_object_detection.py,加入以下代碼,導入你所需要的包。

# import the necessary packagesfrom imutils.video import VideoStreamfrom imutils.video import FPSimport numpy as npimport argparseimport imutilsimport timeimport cv2

2.我們不需要圖像參數,因為在這里我們處理的是視頻流和視頻——除了以下參數保持不變:?prototxt:Caffe prototxt 文件路徑。?model:預訓練模型的路徑。?confidence:過濾弱檢測的最小概率閾值,默認值為 20%。

# construct the argument parse and parse the argumentsap = argparse.ArgumentParser()ap.add_argument('-p', '--prototxt', required=True,help='path to Caffe ’deploy’ prototxt file')ap.add_argument('-m', '--model', required=True,help='path to Caffe pre-trained model')ap.add_argument('-c', '--confidence', type=float, default=0.2,help='minimum probability to filter weak detections')args = vars(ap.parse_args())

3.初始化類列表和顏色集,我們初始化 CLASS 標簽,和相應的隨機 COLORS。

# initialize the list of class labels MobileNet SSD was trained to# detect, then generate a set of bounding box colors for each classCLASSES = ['background', 'aeroplane', 'bicycle', 'bird', 'boat','bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable','dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep','sofa', 'train', 'tvmonitor']COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))

4.加載自己的模型,并設置自己的視頻流。

# load our serialized model from diskprint('[INFO] loading model...')net = cv2.dnn.readNetFromCaffe(args['prototxt'], args['model'])# initialize the video stream, allow the cammera sensor to warmup,# and initialize the FPS counterprint('[INFO] starting video stream...')vs = VideoStream(src=0).start()time.sleep(2.0)fps = FPS().start()

首先我們加載自己的序列化模型,并且提供對自己的 prototxt文件 和模型文件的引用net = cv2.dnn.readNetFromCaffe(args['prototxt'], args['model'])。下一步,我們初始化視頻流(來源可以是視頻文件或攝像頭)。首先,我們啟動 VideoStreamvs = VideoStream(src=0).start(),隨后等待相機啟動time.sleep(2.0),最后開始每秒幀數計算fps = FPS().start()。VideoStream 和 FPS 類是 imutils 包的一部分。

5.遍歷每一幀

# loop over the frames from the video streamwhile True:# grab the frame from the threaded video stream and resize it# to have a maximum width of 400 pixelsframe = vs.read()frame = imutils.resize(frame, width=400)# grab the frame from the threaded video file stream(h, w) = frame.shape[:2]blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)),0.007843, (300, 300), 127.5)# pass the blob through the network and obtain the detections and# predictionsnet.setInput(blob)detections = net.forward()

首先,從視頻流中讀取一幀frame = vs.read(),隨后調整它的大小imutils.resize(frame, width=400)。由于我們隨后會需要寬度和高度,接著進行抓取(h, w) = frame.shape[:2]。最后將 frame 轉換為一個有 dnn 模塊的 blob,cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)),0.007843, (300, 300), 127.5)。現在,我們設置 blob 為神經網絡的輸入net.setInput(blob),通過 net 傳遞輸入detections = net.forward()。

6.這時,我們已經在輸入幀中檢測到了目標,現在看看置信度的值,來判斷我們能否在目標周圍繪制邊界框和標簽。

# loop over the detectionsfor i in np.arange(0, detections.shape[2]):# extract the confidence (i.e., probability) associated with# the predictionconfidence = detections[0, 0, i, 2]# filter out weak detections by ensuring the `confidence` is# greater than the minimum confidenceif confidence > args['confidence']:# extract the index of the class label from the# `detections`, then compute the (x, y)-coordinates of# the bounding box for the objectidx = int(detections[0, 0, i, 1])box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])(startX, startY, endX, endY) = box.astype('int')# draw the prediction on the framelabel = '{}: {:.2f}%'.format(CLASSES[idx],confidence * 100)cv2.rectangle(frame, (startX, startY), (endX, endY),COLORS[idx], 2)y = startY - 15 if startY - 15 > 15 else startY + 15cv2.putText(frame, label, (startX, y),cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)

在 detections 內循環,一個圖像中可以檢測到多個目標。因此我們需要檢查置信度。如果置信度足夠高(高于閾值),那么將在終端展示預測,并以文本和彩色邊界框的形式對圖像作出預測。在 detections 內循環,首先我們提取 confidence 值,confidence = detections[0, 0, i, 2]。如果 confidence 高于最低閾值(if confidence > args['confidence']:),那么提取類標簽索引(idx = int(detections[0, 0, i, 1])),并計算檢測到的目標的坐標(box = detections[0, 0, i, 3:7] * np.array([w, h, w, h]))。然后,我們提取邊界框的 (x, y) 坐標((startX, startY, endX, endY) = box.astype('int')),將用于繪制矩形和文本。接著構建一個文本 label,包含 CLASS 名稱和 confidence(label = '{}: {:.2f}%'.format(CLASSES[idx],confidence * 100))。還要使用類顏色和之前提取的 (x, y) 坐標在物體周圍繪制彩色矩形(cv2.rectangle(frame, (startX, startY), (endX, endY),COLORS[idx], 2))。如果我們希望標簽出現在矩形上方,但是如果沒有空間,我們將在矩形頂部稍下的位置展示標簽(y = startY - 15 if startY - 15 > 15 else startY + 15)。最后,我們使用剛才計算出的 y 值將彩色文本置于幀上(cv2.putText(frame, label, (startX, y),cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2))。

7.幀捕捉循環剩余的步驟還包括:展示幀;檢查 quit 鍵;更新 fps 計數器。

# show the output framecv2.imshow('Frame', frame)key = cv2.waitKey(1) & 0xFF# if the `q` key was pressed, break from the loopif key == ord('q'):break# update the FPS counterfps.update()

上述代碼塊簡單明了,首先我們展示幀(cv2.imshow('Frame', frame)),然后找到特定按鍵(key = cv2.waitKey(1) & 0xFF),同時檢查「q」鍵(代表「quit」)是否按下。如果已經按下,則我們退出幀捕捉循環(if key == ord('q'):break),最后更新 fps 計數器(fps.update())。

8.退出了循環(「q」鍵或視頻流結束),我們還要處理以下。

# stop the timer and display FPS informationfps.stop()print('[INFO] elapsed time: {:.2f}'.format(fps.elapsed()))print('[INFO] approx. FPS: {:.2f}'.format(fps.fps()))# do a bit of cleanupcv2.destroyAllWindows()vs.stop()

運行文件目錄有以下文件:

OpenCV+python實現實時目標檢測功能

到文件相應的目錄下:cd D:目標檢測object-detection執行命令:python real_time_object_detection.py --prototxt MobileNetSSD_deploy.prototxt.txt --model MobileNetSSD_deploy.caffemodel

OpenCV+python實現實時目標檢測功能

演示

這里我把演示視頻上傳到了B站,地址鏈接目標檢測

補充

項目github地址object_detection鏈接。本項目要用到MobileNetSSD_deploy.prototxt.txt和MobileNetSSD_deploy.caffemodel,可以去github上下載項目運行。

到此這篇關于OpenCV+python實現實時目標檢測功能的文章就介紹到這了,更多相關python實現目標檢測內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 国产不卡在线播放 | 国产经典自拍 | 狠狠色丁香婷婷综合久久来 | 51精品视频免费国产专区 | www.日韩三级 | 日本精品一区二区三本中文 | 国产主播久久 | 欧美精品v国产精品v日韩精品 | 大尺度做爰床戏呻吟免费观 | 三黄色片 | 高清国产美女一级a毛片在线 | 亚洲伦理一区二区 | 人与牲动交xxxxbbbb | 国产xxxxx片免费观看 | 国产www | 国产亚洲视频网站 | 免费久久精品视频 | 国产精品成人免费视频 | 亚洲欧洲日韩天堂无吗 | 久久观看 | 又黄又爽又猛大片录像 | 精品国产免费人成在线观看 | 香蕉福利| 婷婷综合国产激情在线 | 成人午夜视频在线观看 | 国产精品日韩高清在线蜜芽 | 日韩一区精品视频在线看 | 成人做爰免视频高清 | 亚洲日本欧美产综合在线 | 亚洲免费看片 | 天天影视欲香欲色成人网 | 国产一级视频久久 | 88国产精品视频一区二区三区 | 国产一区二区网站 | 伊人热 | 亚洲五月婷婷 | 千百橹最新亚洲地址在线播放 | 一级毛片一级黄片 | 亚洲+自拍+色综合图区一 | 天天看a| 国产日产精品_国产精品毛片 |