当前位置:   article > 正文

[opencv]基于dlib和ssd的目标追踪和多线程加速_dlib跟踪算法

dlib跟踪算法

1.opencv的追踪算法

1.1opencv的八个追踪算法

"csrt": cv2.TrackerCSRT_create,
"kcf": cv2.TrackerKCF_create,
"boosting": cv2.TrackerBoosting_create,
"mil": cv2.TrackerMIL_create,
"tld": cv2.TrackerTLD_create,
"medianflow": cv2.TrackerMedianFlow_create,
"mosse": cv2.TrackerMOSSE_create

主要用到 kcf(卡尔曼滤波),效率和准确率都不错

1.2基于kcf的OpenCV追踪检测流程

  1. # 实例化OpenCV's multi-object tracker
  2. trackers = cv2.legacy.MultiTracker_create() #实例化一个追踪器
  3. # 视频流
  4. while True:
  5. # 取当前帧
  6. ret , frame = vs.cv2.VideoCapture(args["video"]) #选择参数列表传入的追踪器
  7. # 到头了就结束
  8. if ret is False:
  9. print("没有视频")
  10. break
  11. # resize每一帧
  12. (h, w) = frame.shape[:2]
  13. width=600
  14. r = width / float(w)
  15. dim = (width, int(h * r))
  16. frame = cv2.resize(frame,
  17. # 追踪结果
  18. (success, boxes) = tracker
  19. # 绘制区域
  20. for box in boxes:
  21. (x, y, w, h) = [int(v)
  22. cv2.rectangle(frame, (
  23. # 显示
  24. cv2.imshow("Frame", frame)
  25. key = cv2.waitKey(100) & 0
  26. if key == ord("s"):
  27. # 选择一个区域,按s
  28. box = cv2.selectROI("F
  29. showCrosshair=True
  30. # 创建一个新的追踪器
  31. tracker = OPENCV_OBJEC
  32. trackers.add(tracker,
  33. # 退出
  34. elif key == 27:
  35. break
  36. vs.release()
  37. cv2.destroyAllWindows()

2.深度学习的追踪算法:ssd(检测器)+dlib(追踪器)

2.1dlib介绍:

它是一个高性能的计算框架。它是一个C++编写的工具包,所以在应用层面的推理速度是非常快的。而且配备了python客户端,很方便开发者在各大平台使用,大大提高了框架的灵活性。

广泛应用于工业界和学术界。包含了大多数常用的机器学习算法,许多图像处理算法和深度学习算法,被工业界和学术界广泛应用于机器人,嵌入式设备,移动电话和大型高性能计算环境领域。常见的深度学习,基于SVM的分类和递归算法,针对大规模分类和递归的降维方法,相关向量机,聚类,多层感知机等都有相关API,且配置详细文档。最重要的一点是开源,开源,开源!这就意味着,我们可以在任何APP上免费试用。

2.2算法流程

  1. '''训练的时候怎么进行数据预处理,测试的时也需要进行相同的预处理'''
  2. if len(tracker) == 0:
  3. #获取blob数据
  4. (h,w) = frame.shape[:2]
  5. #归一化,减均值操作
  6. blob = cv2.dnn.blobFromImage(frame,0.007843,(w,h),127.5)
  7. #得到检测结果
  8. net.setInput(blob)
  9. detections = net.forward()
  10. #遍历得到的检测结果
  11. for i in np.arange(1,detections.shape[2]):
  12. #会有多个结果,只保留概率最高的
  13. confidence = detections[0,0,i,2]
  14. #过滤
  15. if confidence > args["confidence"]:
  16. #将类标签的索引从检测列表中抽取出来
  17. idx = int(detections[0,0,i,1])
  18. label = CLASSES[idx]
  19. #只保留人的
  20. if CLASSES[idx] != 'person':
  21. continue
  22. #得到bbox
  23. #print detections[0,0,i,3:7]
  24. box = detections[0,0,i,3:7] * np.array([w,h,w,h])
  25. (startX,startY,endX,endY) = box.astype('int')
  26. #使用dlib来进行目标追踪
  27. t = dlib.correlation_tracker()
  28. rect = dlib.rectangle(int(startX),int(startY),int(endX),int(endY))
  29. t.start_track(rgb,rect)
  30. #保存结果
  31. labels.append(label)
  32. trackers.append(t)

2.3多进程的追踪流程

  1. def start_tracker(box, label, rgb, inputQueue, outputQueue):
  2. '''后两个参数传入的是队列'''
  3. t = dlib.correlation_tracker() #创建追踪器
  4. rect = dlib.rectangle(int(box[0]), int(box[1]), int(box[2]), int(box[3]))
  5. t.start_track(rgb, rect) #用dlib追踪器的属性去画图
  6. while True:
  7. # 获取下一帧
  8. rgb = inputQueue.get()
  9. # 非空就开始处理
  10. if rgb is not None:
  11. # 更新追踪器
  12. t.update(rgb)
  13. pos = t.get_position()
  14. startX = int(pos.left())
  15. startY = int(pos.top())
  16. endX = int(pos.right())
  17. endY = int(pos.bottom())
  18. # 把结果放到输出q
  19. outputQueue.put((label, (startX, startY, endX, endY)))

多进程处理:主要用到  `import multiprocessing` 工具包

 

  1. from utils import FPS
  2. import multiprocessing
  3. import numpy as np
  4. import argparse
  5. import dlib
  6. import cv2
  7. #perfmon
  8. ap = argparse.ArgumentParser()
  9. ap.add_argument("-p", "--prototxt", required=True,
  10. help="path to Caffe 'deploy' prototxt file")
  11. ap.add_argument("-m", "--model", required=True,
  12. help="path to Caffe pre-trained model")
  13. ap.add_argument("-v", "--video", required=True,
  14. help="path to input video file")
  15. ap.add_argument("-o", "--output", type=str,
  16. help="path to optional output video file")
  17. ap.add_argument("-c", "--confidence", type=float, default=0.2,
  18. help="minimum probability to filter weak detections")
  19. args = vars(ap.parse_args())
  20. # 一会要放多个追踪器
  21. inputQueues = []
  22. outputQueues = []
  23. CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
  24. "bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
  25. "dog", "horse", "motorbike", "person", "pottedplant", "sheep",
  26. "sofa", "train", "tvmonitor"]
  27. print("[INFO] loading model...")
  28. net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])
  29. print("[INFO] starting video stream...")
  30. vs = cv2.VideoCapture(args["video"])
  31. writer = None
  32. fps = FPS().start()
  33. if __name__ == '__main__':
  34. while True:
  35. (grabbed, frame) = vs.read()
  36. if frame is None:
  37. break
  38. (h, w) = frame.shape[:2]
  39. width=600
  40. r = width / float(w)
  41. dim = (width, int(h * r))
  42. frame = cv2.resize(frame, dim, interpolation=cv2.INTER_AREA)
  43. rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
  44. if args["output"] is not None and writer is None:
  45. fourcc = cv2.VideoWriter_fourcc(*"MJPG")
  46. writer = cv2.VideoWriter(args["output"], fourcc, 30,
  47. (frame.shape[1], frame.shape[0]), True)
  48. #首先检测位置
  49. if len(inputQueues) == 0:
  50. (h, w) = frame.shape[:2]
  51. blob = cv2.dnn.blobFromImage(frame, 0.007843, (w, h), 127.5) #推理阶段的图片预处理
  52. net.setInput(blob) #将处理后的图片放入net,再次将网络前向传播
  53. detections = net.forward()
  54. for i in np.arange(0, detections.shape[2]):
  55. confidence = detections[0, 0, i, 2]
  56. if confidence > args["confidence"]:
  57. idx = int(detections[0, 0, i, 1])
  58. label = CLASSES[idx]
  59. if CLASSES[idx] != "person":
  60. continue
  61. box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
  62. (startX, startY, endX, endY) = box.astype("int")
  63. bb = (startX, startY, endX, endY)
  64. # 创建输入q和输出q 多进程
  65. iq = multiprocessing.Queue()
  66. oq = multiprocessing.Queue()
  67. inputQueues.append(iq)
  68. outputQueues.append(oq)
  69. # 多核
  70. p = multiprocessing.Process(
  71. target=start_tracker,
  72. args=(bb, label, rgb, iq, oq)) #Process()函数需要的参数
  73. p.daemon = True
  74. p.start()
  75. cv2.rectangle(frame, (startX, startY), (endX, endY),
  76. (0, 255, 0), 2)
  77. cv2.putText(frame, label, (startX, startY - 15),
  78. cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 2)
  79. else:
  80. # 多个追踪器处理的都是相同输入
  81. for iq in inputQueues:
  82. iq.put(rgb)
  83. for oq in outputQueues:
  84. # 得到更新结果
  85. (label, (startX, startY, endX, endY)) = oq.get()
  86. # 绘图
  87. cv2.rectangle(frame, (startX, startY), (endX, endY),
  88. (0, 255, 0), 2)
  89. cv2.putText(frame, label, (startX, startY - 15),
  90. cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 255, 0), 2)
  91. if writer is not None:
  92. writer.write(frame)
  93. cv2.imshow("Frame", frame)
  94. key = cv2.waitKey(1) & 0xFF
  95. if key == 27:
  96. break
  97. fps.update()
  98. fps.stop()
  99. print("[INFO] elapsed time: {:.2f}".format(fps.elapsed()))
  100. print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))
  101. if writer is not None:
  102. writer.release()
  103. cv2.destroyAllWindows()
  104. vs.release()

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

闽ICP备14008679号