OpenCV DNN模块支持常见得对象检测模型SSD, 以及它的移动版Mobile Net-SSD,特别是后者在端侧边缘设备上可以实时计算,基于Caffe训练好的mobile-net SSD支持20类别对象检测。
在Caffe训练好的mobile-net SSD中内置了"background","aeroplane", "bicycle","bird","boat","bottle","bus","car","cat","chair","cow","diningtable","dog","horse","motorbike","person","pottedplant","sheep","sofa","train","tvmonitor"等20种对象检测。
import cv2 as cv
# 模型路径
model_bin = r"C:\Python\Pycharm\docxprocess\face_detector\ssd\MobileNetSSD_deploy.caffemodel"
config_text = r"C:\Python\Pycharm\docxprocess\face_detector\ssd\MobileNetSSD_deploy.prototxt"
# 类别信息
objName = ["background",
"aeroplane", "bicycle", "bird", "boat",
"bottle", "bus", "car", "cat", "chair",
"cow", "diningtable", "dog", "horse",
"motorbike", "person", "pottedplant",
"sheep", "sofa", "train", "tvmonitor"]
# 加载模型
net = cv.dnn.readNetFromCaffe(config_text, model_bin)
# 读取测试图片
imgname = r'C:\Python\Pycharm\docxprocess\picture\other\renwu\juhui1.jpg'
# imgname = r'C:\Python\Pycharm\docxprocess\picture\other\renwu\juhui2.png'
# imgname = r'C:\Python\Pycharm\docxprocess\picture\other\renwu\juhui3.jpg'
# imgname = r'C:\Python\Pycharm\docxprocess\picture\other\renwu\juhui4.png'
# imgname = r'C:\Python\Pycharm\docxprocess\picture\other\renwu\wukelan.jpeg'
confThreshold = 0.5
image = cv.imread(imgname)
h = image.shape[0]
w = image.shape[1]
# 获得所有层名称与索引
layerNames = net.getLayerNames()
lastLayerId = net.getLayerId(layerNames[-1])
lastLayer = net.getLayer(lastLayerId)
# 检测
blobImage = cv.dnn.blobFromImage(image, 0.007843, (300, 300), (127.5, 127.5, 127.5), True, False)
net.setInput(blobImage)
cvOut = net.forward()
for detection in cvOut[0, 0, :, :]:
score = float(detection[2])
objIndex = int(detection[1])
if score > confThreshold and objName[objIndex]=='person':
left = detection[3] * w
top = detection[4] * h
right = detection[5] * w
bottom = detection[6] * h
# 绘制
cv.rectangle(image, (int(left), int(top)), (int(right), int(bottom)), (255, 0, 0), thickness=2)
cv.putText(image, "score:%.2f, %s" % (score, objName[objIndex]),
(int(left) - 10, int(top) - 5), cv.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2, 8);
# 显示
cv.imshow('mobilenet-ssd-demo', image)
cv.waitKey(0)
cv.destroyAllWindows()
mobile-net SSD通过矩形框的方式标注整个人,可以看到对于遮挡的人识别率较低。
mobile-net SSD对于全身的人的判断还是不错的
mobile-net SSD对于半身和小图片一个都未识别到。
mobile-net SSD对正前方乌克兰妹纸的识别还是不错的
本文分享自 python与大数据分析 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!