当前位置:   article > 正文

使用Python + YOLO+opencv进行目标检测_python+opencv调用摄像头固定间隔时间拍照并保存到本地同时应用到yolo中检测目标

python+opencv调用摄像头固定间隔时间拍照并保存到本地同时应用到yolo中检测目标

完整源码:https://download.csdn.net/download/bibinGee/12278566

 

YOLO相关原理及数据集可以通过这个链接查看:https://pjreddie.com/darknet/yolo/

本博文将介绍使用YOLO结合opencv进行目标检测,需要用到的的资源有coco.names/yolov3.cfg/yolov3.weights,这些文件都可以从darknet或者github上找到。GitHub资源通过这个链接找到:https://github.com/pjreddie/darknet

  1. coco.names
  2. yolov3.cfg
  3. yolov3.weight

需要用的python库有: 

  1. import numpy as np
  2. import argparse
  3. import imutils
  4. import time
  5. import cv2
  6. import os

项目的文件结构如下:

首先加载yolov3.weight和yolov3.cfg文件

  1. # derive the paths to the YOLO weights and model configuration
  2. weightsPath = os.path.sep.join([args["yolo"], "yolov3.weights"])
  3. configPath = os.path.sep.join([args["yolo"], "yolov3.cfg"])
  4. # load our YOLO object detector trained on COCO dataset (80 classes)
  5. print("[INFO] loading YOLO from disk...")
  6. net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)

这里用到了opencv中的 dnn.readNetFromDarknet(),这个是opencv提供的深度神经网络学习的函数,有意思的是它似乎专门给darknet框架写的,如下关于这个函数的注释。

  1. ""
  2. readNetFromDarknet(cfgFile[, darknetModel]) -> retval
  3. . @brief Reads a network model stored in <a href="https://pjreddie.com/darknet/">Darknet</a> model files.
  4. . * @param cfgFile path to the .cfg file with text description of the network architecture.
  5. . * @param darknetModel path to the .weights file with learned network.
  6. . * @returns Network object that ready to do forward, throw an exception in failure cases.
  7. . * @returns Net object.
  8. ""

 接着对输入的图像进行预处理:

  1. blob = cv2.dnn.blobFromImage(image, 1 / 255.0, (416, 416), swapRB=True, crop=False)
  2. net.setInput(blob)

这里用到blogFormImage()这个函数,这个函数主要执行下面3个功能:

  1. 1. 均值减法
  2. 2. 缩放
  3. 3. 频道交换

 

下面就可以对输入的图像进行分类识别了:

  1. # loop over each of the layer outputs
  2. for output in layerOutputs:
  3. # loop over each of the detections
  4. for detection in output:
  5. # extract the class ID and confidence (i.e., probability) of
  6. # the current object detection
  7. scores = detection[5:]
  8. classID = np.argmax(scores)
  9. confidence = scores[classID]
  10. # filter out weak predictions by ensuring the detected
  11. # probability is greater than the minimum probability
  12. if confidence > args["confidence"]:
  13. # scale the bounding box coordinates back relative to the
  14. # size of the image, keeping in mind that YOLO actually
  15. # returns the center (x, y)-coordinates of the bounding
  16. # box followed by the boxes' width and height
  17. box = detection[0:4] * np.array([W, H, W, H])
  18. (centerX, centerY, width, height) = box.astype("int")
  19. # use the center (x, y)-coordinates to derive the top and
  20. # and left corner of the bounding box
  21. x = int(centerX - (width / 2))
  22. y = int(centerY - (height / 2))
  23. # update our list of bounding box coordinates, confidences,
  24. # and class IDs
  25. boxes.append([x, y, int(width), int(height)])
  26. confidences.append(float(confidence))
  27. classIDs.append(classID)

 完成后就可以将目标标注出来了:

  1. # ensure at least one detection exists
  2. if len(idxs) > 0:
  3. # loop over the indexes we are keeping
  4. for i in idxs.flatten():
  5. # extract the bounding box coordinates
  6. (x, y) = (boxes[i][0], boxes[i][1])
  7. (w, h) = (boxes[i][2], boxes[i][3])
  8. # draw a bounding box rectangle and label on the image
  9. color = [int(c) for c in COLORS[classIDs[i]]]
  10. print(color)
  11. cv2.rectangle(image, (x, y), (x + w, y + h), color, 2)
  12. text = "{}: {:.4f}".format(LABELS[classIDs[i]], confidences[i])
  13. cv2.putText(image, text, (x, y - 5), cv2.FONT_ITALIC, 0.5, [0, 0, 0], 2)

 下面是利用yolo提供的数据集和图像例子识别出来的目标,准确率还很高。

然而事情也不是一帆风顺,当输入不在训练好的数据的目标的时,就会识别出错,比如下面两位仁兄就很搞笑了,关键时给出的准确度去到了99%和88%,不得不说有一个专用的训练集真的很重要。

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/391001
推荐阅读
相关标签
  

闽ICP备14008679号