opencv+yolov3实现目标检测

- 日理万妓 2022-11-13 04:20 348阅读 0赞

效果图
20210325163047725.png_pic_center

2021032516351188.png_pic_center 20210325164204392.png_pic_center

代码/font>
语言:python

  1. import cv2 as cv
  2. import argparse
  3. import numpy as np
  4. # Initialize the parameters
  5. confThreshold = 0.25 # Confidence threshold
  6. nmsThreshold = 0.4 # Non-maximum suppression threshold
  7. inpWidth = 320 # Width of network's input image
  8. inpHeight = 320 # Height of network's input image
  9. # Give the configuration and weight files for the model and load the network using them.
  10. modelConfiguration = "Yolo-Fastest-voc/yolo-fastest-xl.cfg"
  11. modelWeights = "Yolo-Fastest-voc/yolo-fastest-xl.weights"
  12. # Load names of classes
  13. classesFile = "voc.names"
  14. classes = None
  15. with open(classesFile, 'rt') as f:
  16. classes = f.read().rstrip('\n').split('\n')
  17. colors = [np.random.randint(0, 255, size=3).tolist() for _ in range(len(classes))]
  18. # Get the names of the output layers
  19. def getOutputsNames(net):
  20. # Get the names of all the layers in the network
  21. layersNames = net.getLayerNames()
  22. # print(dir(net))
  23. # Get the names of the output layers, i.e. the layers with unconnected outputs
  24. return [layersNames[i[0] - 1] for i in net.getUnconnectedOutLayers()]
  25. # Draw the predicted bounding box
  26. def drawPred(classId, conf, left, top, right, bottom):
  27. # Draw a bounding box.
  28. cv.rectangle(frame, (left, top), (right, bottom), (0,0,255), thickness=4)
  29. label = '%.2f' % conf
  30. # Get the label for the class name and its confidence
  31. if classes:
  32. assert (classId < len(classes))
  33. label = '%s:%s' % (classes[classId], label)
  34. # Display the label at the top of the bounding box
  35. labelSize, baseLine = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, 0.5, 1)
  36. top = max(top, labelSize[1])
  37. # cv.rectangle(frame, (left, top - round(1.5 * labelSize[1])), (left + round(1.5 * labelSize[0]), top + baseLine), (255,255,255), cv.FILLED)
  38. cv.putText(frame, label, (left, top-10), cv.FONT_HERSHEY_SIMPLEX, 1, (0,255,0), thickness=2)
  39. # Remove the bounding boxes with low confidence using non-maxima suppression
  40. def postprocess(frame, outs):
  41. frameHeight = frame.shape[0]
  42. frameWidth = frame.shape[1]
  43. classIds = []
  44. confidences = []
  45. boxes = []
  46. # Scan through all the bounding boxes output from the network and keep only the
  47. # ones with high confidence scores. Assign the box's class label as the class with the highest score.
  48. classIds = []
  49. confidences = []
  50. boxes = []
  51. for out in outs:
  52. for detection in out:
  53. scores = detection[5:]
  54. classId = np.argmax(scores)
  55. confidence = scores[classId]
  56. if confidence > confThreshold:
  57. center_x = int(detection[0] * frameWidth)
  58. center_y = int(detection[1] * frameHeight)
  59. width = int(detection[2] * frameWidth)
  60. height = int(detection[3] * frameHeight)
  61. left = int(center_x - width / 2)
  62. top = int(center_y - height / 2)
  63. classIds.append(classId)
  64. confidences.append(float(confidence))
  65. boxes.append([left, top, width, height])
  66. # Perform non maximum suppression to eliminate redundant overlapping boxes with
  67. # lower confidences.
  68. indices = cv.dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold)
  69. for i in indices:
  70. i = i[0]
  71. box = boxes[i]
  72. left = box[0]
  73. top = box[1]
  74. width = box[2]
  75. height = box[3]
  76. drawPred(classIds[i], confidences[i], left, top, left + width, top + height)
  77. if __name__=='__main__':
  78. parser = argparse.ArgumentParser(description='Object Detection using YOLO in OPENCV')
  79. parser.add_argument('--image', type=str, default='person.jpg', help='Path to image file.')
  80. args = parser.parse_args()
  81. net = cv.dnn.readNetFromDarknet(modelConfiguration, modelWeights)
  82. net.setPreferableBackend(cv.dnn.DNN_BACKEND_OPENCV)
  83. net.setPreferableTarget(cv.dnn.DNN_TARGET_CPU)
  84. # Process inputs
  85. frame = cv.imread(args.image)
  86. # Create a 4D blob from a frame.
  87. blob = cv.dnn.blobFromImage(frame, 1/255.0, (inpWidth, inpHeight), [0, 0, 0], swapRB=False, crop=False)
  88. # Sets the input to the network
  89. net.setInput(blob)
  90. # Runs the forward pass to get output of the output layers
  91. outs = net.forward(getOutputsNames(net))
  92. # Remove the bounding boxes with low confidence
  93. postprocess(frame, outs)
  94. # Put efficiency information. The function getPerfProfile returns the overall time for inference(t) and the timings for each of the layers(in layersTimes)
  95. t, _ = net.getPerfProfile()
  96. label = 'Inference time: %.2f ms' % (t * 1000.0 / cv.getTickFrequency())
  97. cv.putText(frame, label, (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255))
  98. winName = 'Deep learning object detection in OpenCV'
  99. cv.namedWindow(winName,0)
  100. cv.imshow(winName, frame)
  101. cv.waitKey(0)
  102. cv.destroyAllWindows()

代码的中图 存放位置 是和资源代码一个文件夹。路径为相对路径
parser.add_argument(’–image’, type=str, default=‘person.jpg’, help=‘Path to image file.’)

所有代码见个人资源:
https://download.csdn.net/download/KOBEYU652453/13082584

在这里插入图片描述
作者:电气余登武
2021032516425296.jpg_pic_center

发表评论

表情:
评论列表 (有 0 条评论,348人围观)

还没有评论,来说两句吧...

相关阅读

    相关 分析YOLOv3目标检测

    前言 YOLOv3模型比之前的模型复杂了,但是精度也提高了。YOLOv3最大的变化包括两点:使用残差模型和采用FPN架构。YOLO2曾采用passthrough结构来检测