最新版本OpenCV4.1.2,針對深度神經網絡模塊,提供了三個類,通過它們,自動實現輸入圖像預處理與後處理,直接輸出檢測結果,支持圖像分類、對象檢測、圖像分割三種常見的視覺常見任務
分別如下:
cv2.dnn_ClassificationModel
cv2.dnn_DetectionModel
cv2.dnn_SegmentationModel
安裝
網址:https://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv
找到對應版本的whl文件,下載到\Lib\site-packages文件夾下,然後pip install +文件名 完成安裝
cv2.dnn_DetectionModel
以OpenCV自帶的SSD人臉檢測爲例,
1. 獲取模型及權重等參數文件
首先需要運行:sources\samples\dnn\face_detector文件夾下的
download_weights.py
得到res10_300x300_ssd_iter_140000_fp16.caffemodel文件
2. 模型加載
import cv2
#.caffemodel 和.prototxt在\sources\samples\dnn\face_detector文件夾下可找到
faceDetect=cv2.dnn_DetectionModel('res10_300x300_ssd_iter_140000_fp16.caffemodel','deploy.prototxt')
3. 檢測函數 cv2.dnn_DetectionModel.detect(frame[, confThreshold[, nmsThreshold]])
參數:
- frame: 輸入的圖像
- confThreshold: 用來過濾選擇框的置信度閾值
- numsThreshold: 非極大值抑制中的閾值
返回:
一個元組,包含(classIds, confidences, boxes)
- classIds: 類別索引(在SSD人臉檢測中,0表示無,1表示有)
- confidences: 置信度
- boxes: 檢測框座標,形式爲(x, y, width, height)
e.g.
img=cv2.imread('xiaolixun.jpg')
detections=faceDetect.detect(img)
print(detections)
輸出:
(array([[1]], dtype=int32), array([[0.99480116]], dtype=float32), array([[202, 79, 78, 90]], dtype=int32))
4. 繪製bounding box
#獲取bounding box信息
x,y,width,height=detections[2][0][0:4]
#繪製bounding box
cv2.rectangle(img, (x, y),(x+width, y+height),(0, 0, 255), 2)
cv2.imshow('detect',img)
cv2.waitKey()
cv2.destroyAllWindows()
顯示如下:
補充:
以往利用dnn模塊進行深度學習時
- 通過net=cv2.dnn.readNetFromCaffe('*','*')加載模型,
- 利用blob=cv2.dnn.blobFromImage進行圖像預處理,
- 利用 net.setInput(blob) detections = net.forward() 獲取檢測結果,
- 最後對detections進行後處理,得到bounding box等相關信息
對比發現新增的API極大地方便了小白調用深度學習相關分類,檢測,分割等模型。
PS:
掃碼關注微信公衆號獲取深度學習數據集,總有一款適合你
我們不生產數據,我們只是數據的搬運工