Guest User

Untitled

a guest
Sep 19th, 2023
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. from ultralytics import YOLO
  2. import cv2
  3. import numpy as np
  4. from ultralytics.utils.plotting import Annotator
  5.  
  6. # Load YOLO model
  7. model = YOLO('best.pt')
  8.  
  9. # Open the video file windows
  10. # cap = cv2.VideoCapture('D:\_PVS\Video\C0012.MP4')
  11.  
  12. # open video file linux
  13. cap = cv2.VideoCapture('/home/boaz/Videos/C0012.MP4')
  14.  
  15.  
  16. # Set the desired resolution (720x1280)
  17. new_width = 1280
  18. new_height = 720
  19.  
  20. # Load the image mask
  21. mask_image = cv2.imread('mask_v2.png', cv2.IMREAD_GRAYSCALE) # image must be black and white
  22. resized_mask = cv2.resize(mask_image, (new_width, new_height))
  23. binary_mask = resized_mask // 255 # Convert to binary mask (0s and 1s)
  24.  
  25. # Initialize car count
  26. car_count = 0
  27.  
  28. # Initialize frame counter
  29. frame_counter = 0
  30.  
  31. while True:
  32. _, frame = cap.read()
  33.  
  34. if frame is None:
  35. break
  36.  
  37. # Increment the frame counter
  38. frame_counter += 1
  39.  
  40. # Process every 24th frame
  41. if frame_counter % 240 != 0:
  42. continue
  43.  
  44. # Resize the frame to the desired resolution
  45. resized_frame = cv2.resize(frame, (new_width, new_height)) # reduce it to 1280 x 720 may be better to keep it
  46. # higher
  47.  
  48. # Apply the binary mask to the resized frame
  49. masked_frame = cv2.bitwise_and(resized_frame, resized_frame, mask=binary_mask)
  50.  
  51. # Convert to RGB
  52. img = cv2.cvtColor(masked_frame, cv2.COLOR_BGR2RGB)
  53.  
  54. # Perform object detection
  55. results = model.predict(masked_frame, conf=0.4, iou=0.7)
  56.  
  57. for r in results:
  58. boxes = r.boxes
  59. for box in boxes:
  60. car_count += 1
  61. b = box.xyxy[0]
  62. annotator = Annotator(resized_frame)
  63. annotator.box_label(b)
  64.  
  65. frame_with_boxes = annotator.result()
  66. cv2.imshow('YOLO V8 Detection', frame_with_boxes)
  67.  
  68. # Calculate remaining count
  69. remaining_count = 75 - car_count
  70.  
  71. # Print the remaining count
  72. print(f'Remaining Count: {remaining_count}')
  73.  
  74. # Reset car count
  75. car_count = 0
  76.  
  77. if cv2.waitKey(1) & 0xFF == ord(' '): # if you press the space-bar key, it stops the program
  78. break
  79.  
  80. cap.release()
  81. cv2.destroyAllWindows()
  82.  
Advertisement
Add Comment
Please, Sign In to add comment