OpenCV4.1.2新增的cv2.dnn_DetectionModel 类的用法

最新版本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模块进行深度学习时

  1. 通过net=cv2.dnn.readNetFromCaffe('*','*')加载模型
  2. 利用blob=cv2.dnn.blobFromImage进行图像预处理
  3. 利用 net.setInput(blob) detections = net.forward() 获取检测结果
  4. 最后对detections进行后处理,得到bounding box等相关信息

对比发现新增的API极大地方便了小白调用深度学习相关分类,检测,分割等模型。

发布了29 篇原创文章 · 获赞 26 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_42216109/article/details/103015617