darknet_video.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. from ctypes import *
  2. import math
  3. import random
  4. import os
  5. import cv2
  6. import numpy as np
  7. import time
  8. import darknet
  9. def convertBack(x, y, w, h):
  10. xmin = int(round(x - (w / 2)))
  11. xmax = int(round(x + (w / 2)))
  12. ymin = int(round(y - (h / 2)))
  13. ymax = int(round(y + (h / 2)))
  14. return xmin, ymin, xmax, ymax
  15. def cvDrawBoxes(detections, img):
  16. for detection in detections:
  17. x, y, w, h = detection[2][0],\
  18. detection[2][1],\
  19. detection[2][2],\
  20. detection[2][3]
  21. xmin, ymin, xmax, ymax = convertBack(
  22. float(x), float(y), float(w), float(h))
  23. pt1 = (xmin, ymin)
  24. pt2 = (xmax, ymax)
  25. cv2.rectangle(img, pt1, pt2, (0, 255, 0), 1)
  26. cv2.putText(img,
  27. detection[0].decode() +
  28. " [" + str(round(detection[1] * 100, 2)) + "]",
  29. (pt1[0], pt1[1] - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
  30. [0, 255, 0], 2)
  31. return img
  32. netMain = None
  33. metaMain = None
  34. altNames = None
  35. def YOLO():
  36. global metaMain, netMain, altNames
  37. configPath = "./cfg/yolov3.cfg"
  38. weightPath = "./yolov3.weights"
  39. metaPath = "./cfg/coco.data"
  40. if not os.path.exists(configPath):
  41. raise ValueError("Invalid config path `" +
  42. os.path.abspath(configPath)+"`")
  43. if not os.path.exists(weightPath):
  44. raise ValueError("Invalid weight path `" +
  45. os.path.abspath(weightPath)+"`")
  46. if not os.path.exists(metaPath):
  47. raise ValueError("Invalid data file path `" +
  48. os.path.abspath(metaPath)+"`")
  49. if netMain is None:
  50. netMain = darknet.load_net_custom(configPath.encode(
  51. "ascii"), weightPath.encode("ascii"), 0, 1) # batch size = 1
  52. if metaMain is None:
  53. metaMain = darknet.load_meta(metaPath.encode("ascii"))
  54. if altNames is None:
  55. try:
  56. with open(metaPath) as metaFH:
  57. metaContents = metaFH.read()
  58. import re
  59. match = re.search("names *= *(.*)$", metaContents,
  60. re.IGNORECASE | re.MULTILINE)
  61. if match:
  62. result = match.group(1)
  63. else:
  64. result = None
  65. try:
  66. if os.path.exists(result):
  67. with open(result) as namesFH:
  68. namesList = namesFH.read().strip().split("\n")
  69. altNames = [x.strip() for x in namesList]
  70. except TypeError:
  71. pass
  72. except Exception:
  73. pass
  74. #cap = cv2.VideoCapture(0)
  75. cap = cv2.VideoCapture("test.mp4")
  76. cap.set(3, 1280)
  77. cap.set(4, 720)
  78. out = cv2.VideoWriter(
  79. "output.avi", cv2.VideoWriter_fourcc(*"MJPG"), 10.0,
  80. (darknet.network_width(netMain), darknet.network_height(netMain)))
  81. print("Starting the YOLO loop...")
  82. # Create an image we reuse for each detect
  83. darknet_image = darknet.make_image(darknet.network_width(netMain),
  84. darknet.network_height(netMain),3)
  85. while True:
  86. prev_time = time.time()
  87. ret, frame_read = cap.read()
  88. frame_rgb = cv2.cvtColor(frame_read, cv2.COLOR_BGR2RGB)
  89. frame_resized = cv2.resize(frame_rgb,
  90. (darknet.network_width(netMain),
  91. darknet.network_height(netMain)),
  92. interpolation=cv2.INTER_LINEAR)
  93. darknet.copy_image_from_bytes(darknet_image,frame_resized.tobytes())
  94. detections = darknet.detect_image(netMain, metaMain, darknet_image, thresh=0.25)
  95. image = cvDrawBoxes(detections, frame_resized)
  96. image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
  97. print(1/(time.time()-prev_time))
  98. cv2.imshow('Demo', image)
  99. cv2.waitKey(3)
  100. cap.release()
  101. out.release()
  102. if __name__ == "__main__":
  103. YOLO()