import cv2
from ultralytics import YOLO
# Load the pre-trained YOLOv8 model
model = YOLO('yolov8n.pt') # Replace 'yolov8n.pt' with the actual path to your YOLOv8 model checkpoint
# Initialize video capture from the specified file path
video_path = r"C:\Users\Desktop\archive\Test Video.mp4"
cap = cv2.VideoCapture(video_path)
# Get the frame rate of the video
frame_rate = cap.get(cv2.CAP_PROP_FPS)
# Initialize counter for vehicles that crossed the virtual line
crossed_count = 0
# Virtual line position
virtual_line_y = 550
# Define a range around the virtual line position to account for variations in detection
line_range = 5 # Adjust this value as needed
while True:
ret, frame = cap.read()
if not ret:
break
# Draw virtual line at position 550
cv2.line(frame, (0, virtual_line_y), (frame.shape[1], virtual_line_y), (0, 0, 255), 2) # Red line
# Perform object detection
detections = model(frame)
# Iterate over the detections
for det in detections:
for box in det.boxes:
# Get bounding box coordinates
bbox = box.xyxy.int().flatten().tolist()
# Draw bounding box
cv2.rectangle(frame, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2)
# Display position
position = (bbox[0], bbox[1])
cv2.putText(frame, f'Position: {position}', (bbox[0], bbox[1] + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
# Check if the y-coordinate of the vehicle is within the range of the virtual line position
if virtual_line_y - line_range <= bbox[1] <= virtual_line_y + line_range:
crossed_count += 1
# Display crossed vehicle count at the center of the frame
cv2.putText(frame, f'Crossed Count: {crossed_count}', (int(frame.shape[1]/2) - 100, int(frame.shape[0]/2)),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2)
# Display the processed frame
cv2.imshow('Frame', frame)
# Check for 'q' key press to exit
if cv2.waitKey(10) & 0xFF == ord('q'):
break
# Release video capture and close window
cap.release()
cv2.destroyAllWindows()
My problem solution I wanted that when the vehicle hit the virtual line, it should counted as 1, increment the counter with each vehicle crossing the virtual line. boundry box shall be displayed whiole detectin the vehicle. It should not count the frames. I used video from kaggle, though i ll work on real time camera.
I was expecting that boundry box detected over frames shall not be counted again n again , while it should be only counted once. each vehicle shall be assigned with unique id, which does not changed over motion .