hb-setosys commited on
Commit
c4b969e
·
verified ·
1 Parent(s): 9d7a67b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -0
app.py CHANGED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import numpy as np
4
+ import torch
5
+ from ultralytics import YOLO
6
+ from sort import Sort
7
+ import gradio as gr
8
+
9
+ # Load YOLOv12x model
10
+ MODEL_PATH = "yolov12x.pt"
11
+ model = YOLO(MODEL_PATH)
12
+
13
+ # COCO dataset class ID for truck
14
+ TRUCK_CLASS_ID = 7 # "truck"
15
+
16
+ # Initialize SORT tracker
17
+ tracker = Sort()
18
+
19
+ # Minimum confidence threshold for detection
20
+ CONFIDENCE_THRESHOLD = 0.4 # Lowered for better detection
21
+
22
+ # Distance threshold to avoid duplicate counts
23
+ DISTANCE_THRESHOLD = 50
24
+
25
+ # Dictionary to define keyword-based time intervals
26
+ TIME_INTERVALS = {
27
+ "one": 1, "two": 2, "three": 3, "four": 4, "five": 5,
28
+ "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10, "eleven": 11
29
+ }
30
+
31
+ def determine_time_interval(video_filename):
32
+ """ Determines frame skip interval based on keywords in the filename. """
33
+ print(f"Checking filename: {video_filename}") # Debugging
34
+ for keyword, interval in TIME_INTERVALS.items():
35
+ if keyword in video_filename:
36
+ print(f"Matched keyword: {keyword} -> Interval: {interval}") # Debugging
37
+ return interval
38
+ print("No keyword match, using default interval: 5") # Debugging
39
+ return 5 # Default interval
40
+
41
+ def count_unique_trucks(video_path):
42
+ """ Counts unique trucks in a video using YOLOv12x and SORT tracking. """
43
+ cap = cv2.VideoCapture(video_path)
44
+ if not cap.isOpened():
45
+ return {"Error": "Unable to open video file."}
46
+
47
+ # Reset variables at the start of each analysis
48
+ unique_truck_ids = set()
49
+ truck_history = {}
50
+
51
+ # Get FPS of the video
52
+ fps = int(cap.get(cv2.CAP_PROP_FPS))
53
+
54
+ # Extract filename from the path and convert to lowercase
55
+ video_filename = os.path.basename(video_path).lower()
56
+
57
+ # Determine the dynamic time interval based on filename keywords
58
+ time_interval = determine_time_interval(video_filename)
59
+
60
+ # Get total frames in the video
61
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
62
+
63
+ # Ensure frame_skip does not exceed total frames
64
+ frame_skip = min(fps * time_interval, total_frames // 2) # Reduced skipping
65
+
66
+ frame_count = 0
67
+
68
+ # Reinitialize the tracker to clear any previous state
69
+ tracker = Sort()
70
+
71
+ while True:
72
+ ret, frame = cap.read()
73
+ if not ret:
74
+ break # End of video
75
+
76
+ frame_count += 1
77
+ if frame_count % frame_skip != 0:
78
+ continue # Skip frames based on interval
79
+
80
+ # Run YOLOv12x inference
81
+ results = model(frame, verbose=False)
82
+
83
+ detections = []
84
+ for result in results:
85
+ for box in result.boxes:
86
+ class_id = int(box.cls.item()) # Get class ID
87
+ confidence = float(box.conf.item()) # Get confidence score
88
+
89
+ # Track only trucks
90
+ if class_id == TRUCK_CLASS_ID and confidence > CONFIDENCE_THRESHOLD:
91
+ x1, y1, x2, y2 = map(int, box.xyxy[0]) # Get bounding box
92
+ detections.append([x1, y1, x2, y2, confidence])
93
+
94
+ # Debugging: Check detections
95
+ print(f"Frame {frame_count}: Detections -> {detections}")
96
+
97
+ if len(detections) > 0:
98
+ detections = np.array(detections)
99
+ tracked_objects = tracker.update(detections)
100
+ else:
101
+ tracked_objects = [] # Prevent tracker from resetting
102
+
103
+ # Debugging: Check tracked objects
104
+ print(f"Frame {frame_count}: Tracked Objects -> {tracked_objects}")
105
+
106
+ for obj in tracked_objects:
107
+ truck_id = int(obj[4]) # Unique ID assigned by SORT
108
+ x1, y1, x2, y2 = obj[:4] # Get the bounding box coordinates
109
+
110
+ truck_center = (x1 + x2) / 2, (y1 + y2) / 2 # Calculate truck center
111
+
112
+ # If truck is already in history, check movement distance
113
+ if truck_id in truck_history:
114
+ last_position = truck_history[truck_id]["position"]
115
+ distance = np.linalg.norm(np.array(truck_center) - np.array(last_position))
116
+
117
+ if distance > DISTANCE_THRESHOLD:
118
+ unique_truck_ids.add(truck_id) # Add only if moved significantly
119
+
120
+ else:
121
+ # If truck is not in history, add it
122
+ truck_history[truck_id] = {
123
+ "frame_count": frame_count,
124
+ "position": truck_center
125
+ }
126
+ unique_truck_ids.add(truck_id)
127
+
128
+ cap.release()
129
+ return {"Total Unique Trucks": len(unique_truck_ids)}
130
+
131
+
132
+ # Gradio UI function
133
+ def analyze_video(video_file):
134
+ result = count_unique_trucks(video_file)
135
+ return "\n".join([f"{key}: {value}" for key, value in result.items()])
136
+
137
+ # Define Gradio interface
138
+ iface = gr.Interface(
139
+ fn=analyze_video,
140
+ inputs=gr.Video(label="Upload Video"),
141
+ outputs=gr.Textbox(label="Analysis Result"),
142
+ title="YOLOv12x Unique Truck Counter",
143
+ description="Upload a video to count unique trucks using YOLOv12x and SORT tracking."
144
+ )
145
+
146
+ # Launch the Gradio app
147
+ if __name__ == "__main__":
148
+ iface.launch()