四时宝库

程序员的知识宝库

20年AI经验大佬深度解析基于深度学习和OpenCV实现目标检测

这篇文章主要介绍了通过使用OpenCV进行基于深度学习的对象检测以及使用OpenCV检测视频,文中的示例代码讲解详细,需要的可以参考一下

目录

  • 使用深度学习和 OpenCV 进行目标检测
  • MobileNets:高效(深度)神经网络
  • 使用 OpenCV 进行基于深度学习的对象检测
  • 使用 OpenCV 检测视频


使用深度学习和 OpenCV 进行目标检测

基于深度学习的对象检测时,您可能会遇到三种主要的对象检测方法:

Faster R-CNNs (Ren et al., 2015)

You Only Look Once (YOLO) (Redmon et al., 2015)

Single Shot Detectors (SSD)(Liu 等人,2015 年)

Faster R-CNNs 可能是使用深度学习进行对象检测最“听说”的方法;然而,该技术可能难以理解(特别是对于深度学习的初学者)、难以实施且难以训练。

此外,即使使用“更快”的 R-CNN 实现(其中“R”代表“区域提议”),算法也可能非常慢,大约为 7 FPS。

如果追求纯粹的速度,那么我们倾向于使用 YOLO,因为这种算法要快得多,能够在 Titan X GPU 上处理 40-90 FPS。 YOLO 的超快变体甚至可以达到 155 FPS。

YOLO 的问题在于它的准确性不高。

最初由 Google 开发的 SSD 是两者之间的平衡。该算法比 Faster R-CNN 更直接。


MobileNets:高效(深度)神经网络

在构建对象检测网络时,我们通常使用现有的网络架构,例如 VGG 或 ResNet,这些网络架构可能非常大,大约 200-500MB。 由于其庞大的规模和由此产生的计算数量,诸如此类的网络架构不适合资源受限的设备。 相反,我们可以使用 Google 研究人员的另一篇论文 MobileNets(Howard 等人,2017 年)。我们称这些网络为“MobileNets”,因为它们专为资源受限的设备而设计,例如您的智能手机。 MobileNet 与传统 CNN 的不同之处在于使用了深度可分离卷积。 深度可分离卷积背后的一般思想是将卷积分成两个阶段:

  • 3×3 深度卷积。
  • 随后是 1×1 逐点卷积

这使我们能够实际减少网络中的参数数量。 问题是牺牲了准确性——MobileNets 通常不如它们的大哥们准确…… ……但它们的资源效率要高得多。


使用 OpenCV 进行基于深度学习的对象检测

MobileNet SSD 首先在 COCO 数据集(上下文中的常见对象)上进行训练,然后在 PASCAL VOC 上进行微调,达到 72.7% mAP(平均精度)。

因此,我们可以检测图像中的 20 个对象(背景类为 +1),包括飞机、自行车、鸟、船、瓶子、公共汽车、汽车、猫、椅子、牛、餐桌、狗、马、摩托车、人、盆栽 植物、羊、沙发、火车和电视显示器。

在本节中,我们将使用 OpenCV 中的 MobileNet SSD + 深度神经网络 (dnn) 模块来构建我们的目标检测器。

打开一个新文件,将其命名为 object_detection.py ,并插入以下代码:

  1. | import numpy as np
  2. | import cv2
  3. | if __name__=="__main__":
  4. | image_name = '11.jpg'
  5. | prototxt = 'MobileNetSSD_deploy.prototxt.txt'
  6. | model_path = 'MobileNetSSD_deploy.caffemodel'
  7. | confidence_ta = 0.2
  8. | # 初始化MobileNet SSD训练的类标签列表
  9. | # 检测,然后为每个类生成一组边界框颜色
  10. | CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
  11. | "bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
  12. | "dog", "horse", "motorbike", "person", "pottedplant", "sheep",
  13. | "sofa", "train", "tvmonitor"]
  14. | COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))

导入需要的包。

定义全局参数:

  • image_name:输入图像的路径。
  • prototxt :Caffe prototxt 文件的路径。
  • model_path :预训练模型的路径。
  • confidence_ta :过滤弱检测的最小概率阈值。 默认值为 20%。

接下来,让我们初始化类标签和边界框颜色。

  1. | # load our serialized model from disk
  2. | print("[INFO] loading model...")
  3. | net = cv2.dnn.readNetFromCaffe(prototxt, model_path)
  4. | # 加载输入图像并为图像构造一个输入blob
  5. | # 将大小调整为固定的300x300像素。
  6. | # (注意:SSD模型的输入是300x300像素)
  7. | image = cv2.imread(image_name)
  8. | (h, w) = image.shape[:2]
  9. | blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 0.007843,
  10. | (300, 300), 127.5)
  11. | # 通过网络传递blob并获得检测结果和
  12. | # 预测
  13. | print("[INFO] computing object detections...")
  14. | net.setInput(blob)
  15. | detections = net.forward()


从磁盘加载模型。

读取图片。

提取高度和宽度(第 35 行),并从图像中计算一个 300 x 300 像素的 blob。

将blob放入神经网络。

计算输入的前向传递,将结果存储为 detections。

  1. | # 循环检测结果
  2. | for i in np.arange(0, detections.shape[2]):
  3. | # 提取与数据相关的置信度(即概率)
  4. | # 预测
  5. | confidence = detections[0, 0, i, 2]
  6. | # 通过确保“置信度”来过滤掉弱检测
  7. | # 大于最小置信度
  8. | if confidence > confidence_ta:
  9. | # 从`detections`中提取类标签的索引,
  10. | # 然后计算物体边界框的 (x, y) 坐标
  11. | idx = int(detections[0, 0, i, 1])
  12. | box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
  13. | (startX, startY, endX, endY) = box.astype("int")
  14. | # 显示预测
  15. | label = "{}: {:.2f}%".format(CLASSES[idx], confidence * 100)
  16. | print("[INFO] {}".format(label))
  17. | cv2.rectangle(image, (startX, startY), (endX, endY),
  18. | COLORS[idx], 2)
  19. | y = startY - 15 if startY - 15 > 15 else startY + 15
  20. | cv2.putText(image, label, (startX, y),
  21. | cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)
  22. | # show the output image
  23. | cv2.imshow("Output", image)
  24. | cv2.imwrite("output.jpg", image)
  25. | cv2.waitKey(0)


循环检测,首先我们提取置信度值。

如果置信度高于我们的最小阈值,我们提取类标签索引并计算检测到的对象周围的边界框。

然后,提取框的 (x, y) 坐标,我们将很快使用它来绘制矩形和显示文本。

接下来,构建一个包含 CLASS 名称和置信度的文本标签。

使用标签,将其打印到终端,然后使用之前提取的 (x, y) 坐标在对象周围绘制一个彩色矩形。

通常,希望标签显示在矩形上方,但如果没有空间,我们会将其显示在矩形顶部下方。

最后,使用刚刚计算的 y 值将彩色文本覆盖到图像上。

运行结果:

使用 OpenCV 检测视频

打开一个新文件,将其命名为 video_object_detection.py ,并插入以下代码:

  1. | video_name = '12.mkv'
  2. | prototxt = 'MobileNetSSD_deploy.prototxt.txt'
  3. | model_path = 'MobileNetSSD_deploy.caffemodel'
  4. | confidence_ta = 0.2
  5. | # initialize the list of class labels MobileNet SSD was trained to
  6. | # detect, then generate a set of bounding box colors for each class
  7. | CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
  8. | "bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
  9. | "dog", "horse", "motorbike", "person", "pottedplant", "sheep",
  10. | "sofa", "train", "tvmonitor"]
  11. | COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))
  12. | # load our serialized model from disk
  13. | print("[INFO] loading model...")
  14. | net = cv2.dnn.readNetFromCaffe(prototxt, model_path)
  15. | # initialze the video stream, allow the camera to sensor to warmup,
  16. | # and initlaize the FPS counter
  17. | print('[INFO] starting video stream...')
  18. | vs = cv2.VideoCapture(video_name)
  19. | fps = 30 #保存视频的FPS,可以适当调整
  20. | size=(600,325)
  21. | fourcc=cv2.VideoWriter_fourcc(*'XVID')
  22. | videowrite=cv2.VideoWriter('output.avi',fourcc,fps,size)
  23. | time.sleep(2.0)


定义全局参数:

  • video_name:输入视频的路径。
  • prototxt :Caffe prototxt 文件的路径。
  • model_path :预训练模型的路径。
  • confidence_ta :过滤弱检测的最小概率阈值。 默认值为 20%。

接下来,让我们初始化类标签和边界框颜色。

加载模型。

初始化VideoCapture对象。

设置VideoWriter对象以及参数。size的大小由下面的代码决定,需要保持一致,否则不能保存视频。

接下就是循环视频的帧,然后输入到检测器进行检测,这一部分的逻辑和图像检测一致。代码如下:

  1. | # loop over the frames from the video stream
  2. | while True:
  3. | ret_val, frame = vs.read()
  4. | if ret_val is False:
  5. | break
  6. | frame = imutils.resize(frame, width=1080)
  7. | print(frame.shape)
  8. | # grab the frame dimentions and convert it to a blob
  9. | (h, w) = frame.shape[:2]
  10. | blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 0.007843, (300, 300), 1| 27.5)
  11. | # pass the blob through the network and obtain the detections and predictions
  12. | net.setInput(blob)
  13. | detections = net.forward()
  14. | # loop over the detections
  15. | for i in np.arange(0, detections.shape[2]):
  16. | # extract the confidence (i.e., probability) associated with
  17. | # the prediction
  18. | confidence = detections[0, 0, i, 2]
  19. | # filter out weak detections by ensuring the `confidence` is
  20. | # greater than the minimum confidence
  21. | if confidence > confidence_ta:
  22. | # extract the index of the class label from the
  23. | # `detections`, then compute the (x, y)-coordinates of
  24. | # the bounding box for the object
  25. | idx = int(detections[0, 0, i, 1])
  26. | box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
  27. | (startX, startY, endX, endY) = box.astype("int")
  28. | # draw the prediction on the frame
  29. | label = "{}: {:.2f}%".format(CLASSES[idx],
  30. | confidence * 100)
  31. | cv2.rectangle(frame, (startX, startY), (endX, endY),
  32. | COLORS[idx], 2)
  33. | y = startY - 15 if startY - 15 > 15 else startY + 15
  34. | cv2.putText(frame, label, (startX, y),
  35. | cv2.FONT_HERSHEY_SIMPLEX, 0.5, COLORS[idx], 2)
  36. | # show the output frame
  37. | cv2.imshow("Frame", frame)
  38. | videowrite.write(frame)
  39. | key = cv2.waitKey(1) & 0xFF
  40. | # if the `q` key was pressed, break from the loop
  41. | if key == ord("q"):
  42. | break
  43. | videowrite.release()
  44. | # do a bit of cleanup
  45. | cv2.destroyAllWindows()
  46. | vs.release()


运行结果:

(B站):https://www.bilibili.com/video/BV1h8411c7zk/?spm_id_from=333.337.search-card.all.click&vd_source=b2d0f4c8b7d5e055a1426385d0f0fd5b

以上就是基于深度学习和OpenCV实现目标检测的详细内容,更多关于深度学习 OpenCV目标检测的资料请关注小编其它相关文章!


准备了100G人工智能学习礼包:

1:人工智能详细学习路线图、大纲

2:300本人工智能经典书籍

3:机器学习算法+深度学习神经网络学习教程

4:计算机视觉论文合集

5:人工智能实战项目合集(附源码)

6、人工智能笔试、面试题

【还有更多学习笔记,评论区:666,先到先得!】

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接