Format: text/x-python
⬇ Download File (1.4 KB)
   1  import cv2
   2  from tracker import *
   3  
   4  # Create tracker object
   5  tracker = EuclideanDistTracker()
   6  
   7  cap = cv2.VideoCapture("highway.mp4")
   8  
   9  # Object detection from Stable camera
  10  object_detector = cv2.createBackgroundSubtractorMOG2(history=100, varThreshold=40)
  11  
  12  while True:
  13      ret, frame = cap.read()
  14      height, width, _ = frame.shape
  15  
  16      # Extract Region of interest
  17      roi = frame[340: 720,500: 800]
  18  
  19      # 1. Object Detection
  20      mask = object_detector.apply(roi)
  21      _, mask = cv2.threshold(mask, 254, 255, cv2.THRESH_BINARY)
  22      contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  23      detections = []
  24      for cnt in contours:
  25          # Calculate area and remove small elements
  26          area = cv2.contourArea(cnt)
  27          if area > 100:
  28              #cv2.drawContours(roi, [cnt], -1, (0, 255, 0), 2)
  29              x, y, w, h = cv2.boundingRect(cnt)
  30  
  31  
  32              detections.append([x, y, w, h])
  33  
  34      # 2. Object Tracking
  35      boxes_ids = tracker.update(detections)
  36      for box_id in boxes_ids:
  37          x, y, w, h, id = box_id
  38          cv2.putText(roi, str(id), (x, y - 15), cv2.FONT_HERSHEY_PLAIN, 2, (255, 0, 0), 2)
  39          cv2.rectangle(roi, (x, y), (x + w, y + h), (0, 255, 0), 3)
  40  
  41      cv2.imshow("roi", roi)
  42      cv2.imshow("Frame", frame)
  43      cv2.imshow("Mask", mask)
  44  
  45      key = cv2.waitKey(30)
  46      if key == 27:
  47          break
  48  
  49  cap.release()
  50  cv2.destroyAllWindows()