rajesh9698 commited on
Commit
7bd53be
·
verified ·
1 Parent(s): 27fd61d

Deploy: backend/wrong_parking_detector.py

Browse files
Files changed (1) hide show
  1. backend/wrong_parking_detector.py +205 -0
backend/wrong_parking_detector.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from ultralytics import YOLO
4
+ import json
5
+ import os
6
+
7
+ class WrongParkingDetector:
8
+ def __init__(self, model_path='yolov8n.pt', slots=None):
9
+ """
10
+ Tactical Violation Detector Core.
11
+ Identifies infractions: Outside Slot, Double Parking, and Slot Conflicts.
12
+ """
13
+ self.model = YOLO(model_path)
14
+ self.slots = slots if slots else []
15
+ self.iou_outside_threshold = 0.5
16
+ self.iou_double_threshold = 0.15
17
+ self.min_car_area = 1500 # Ignore small background detections (noise)
18
+
19
+ # Load from calibration.json if not provided
20
+ if not self.slots:
21
+ try:
22
+ cal_path = os.path.join(os.path.dirname(__file__), "calibration.json")
23
+ if os.path.exists(cal_path):
24
+ with open(cal_path, "r") as f:
25
+ data = json.load(f)
26
+ self.slots = [s["points"] for s in data["slots"]]
27
+ print(f"[VIOLATION] Loaded {len(self.slots)} slots for monitoring.")
28
+ except Exception as e:
29
+ print(f"[ERROR] Failed to load calibration: {e}")
30
+
31
+ def update_slots(self, new_slots):
32
+ """Topology Sync: Update the tactical grid registry."""
33
+ if new_slots:
34
+ self.slots = new_slots
35
+
36
+ def compute_iou(self, boxA, boxB):
37
+ """Standard Intersection over Union (IoU) calculation."""
38
+ y1A, x1A, y2A, x2A = boxA
39
+ y1B, x1B, y2B, x2B = boxB
40
+
41
+ xA = max(x1A, x1B)
42
+ yA = max(y1A, y1B)
43
+ xB = min(x2A, x2B)
44
+ yB = min(y2A, y2B)
45
+
46
+ interArea = max(0, xB - xA) * max(0, yB - yA)
47
+ boxAArea = (x2A - x1A) * (y2A - y1A)
48
+ boxBArea = (x2B - x1B) * (y2B - y1B)
49
+
50
+ iou = interArea / float(boxAArea + boxBArea - interArea + 1e-5)
51
+ return iou
52
+
53
+ def analyze_frame(self, frame, detected_cars=None):
54
+ """
55
+ Analyzes a single frame for parking violations.
56
+ Optimized for Unified Inference: If detected_cars are provided, internal YOLO is bypassed.
57
+ """
58
+ if detected_cars is None:
59
+ # Fallback to internal scan if no external boxes are provided
60
+ results = self.model(frame, classes=[2, 3, 5, 7], verbose=False, conf=0.15)[0]
61
+ detected_cars = []
62
+ if results.boxes:
63
+ for box in results.boxes:
64
+ x1, y1, x2, y2 = map(int, box.xyxy[0])
65
+ # Rule: Size Intensity Filter
66
+ area = (x2 - x1) * (y2 - y1)
67
+ if area > self.min_car_area:
68
+ detected_cars.append([y1, x1, y2, x2])
69
+
70
+ violations = []
71
+ car_assignments = [] # To track which slots a car occupies
72
+
73
+ # 1. ---------------- DETECTION LOGIC ----------------
74
+ for car in detected_cars:
75
+ overlapping_slots = []
76
+ max_iou = 0
77
+
78
+ for i, slot in enumerate(self.slots):
79
+ iou = self.compute_iou(slot, car)
80
+ if iou > 0:
81
+ overlapping_slots.append({"id": i+1, "iou": iou})
82
+ if iou > max_iou: max_iou = iou
83
+
84
+ # Rule 3 & 4: Determine Status
85
+ status = "OK"
86
+ color = (0, 255, 0) # Green
87
+
88
+ # Rule: Outside Parking Detection
89
+ if max_iou < self.iou_outside_threshold:
90
+ status = "Outside Parking"
91
+ color = (0, 0, 255) # Red
92
+
93
+ # Rule: Double Parking Detection (overlaps multiple slots significantly)
94
+ significant_overlaps = [s for s in overlapping_slots if s["iou"] > self.iou_double_threshold]
95
+ if len(significant_overlaps) > 1:
96
+ status = "Double Parking"
97
+ color = (0, 255, 255) # Yellow
98
+
99
+ car_assignments.append({
100
+ "box": car,
101
+ "status": status,
102
+ "color": color,
103
+ "slots": overlapping_slots
104
+ })
105
+
106
+ # Rule 5: Conflict / Double Occupancy Validation
107
+ slot_occupancy = {} # slot_id: [car_indices]
108
+ for idx, assign in enumerate(car_assignments):
109
+ for s in assign["slots"]:
110
+ if s["iou"] > 0.4: # Significant occupancy
111
+ slot_id = s["id"]
112
+ if slot_id not in slot_occupancy: slot_occupancy[slot_id] = []
113
+ slot_occupancy[slot_id].append(idx)
114
+
115
+ # 2. ---------------- VISUALIZATION ----------------
116
+ counts = {"total": len(detected_cars), "outside": 0, "double": 0, "conflict": 0}
117
+
118
+ for idx, assign in enumerate(car_assignments):
119
+ y1, x1, y2, x2 = assign["box"]
120
+ status = assign["status"]
121
+ color = assign["color"]
122
+
123
+ if status == "Outside Parking": counts["outside"] += 1
124
+ if status == "Double Parking": counts["double"] += 1
125
+
126
+ # Check for Conflict Status Enhancement
127
+ final_label = status
128
+ is_conflict = False
129
+ for s in assign["slots"]:
130
+ if s["id"] in slot_occupancy and len(slot_occupancy[s["id"]]) > 1:
131
+ is_conflict = True
132
+ break
133
+
134
+ if is_conflict and status == "OK":
135
+ final_label = "Conflict"
136
+ counts["conflict"] += 1
137
+ color = (255, 128, 0) # Orange for conflict
138
+
139
+ # Draw
140
+ cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
141
+ cv2.putText(frame, final_label, (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
142
+
143
+ # 3. ---------------- STATS OVERLAY ----------------
144
+ active_details = []
145
+ for assign in car_assignments:
146
+ if assign["status"] == "Double Parking":
147
+ slot_ids = [str(s["id"]) for s in assign["slots"] if s["iou"] > 0.1]
148
+ active_details.append({
149
+ "type": "DOUBLE PARKING",
150
+ "msg": f"Vehicle straddling Slots {', '.join(slot_ids)}",
151
+ "level": "Warning",
152
+ "color": "#eab308"
153
+ })
154
+ elif assign["status"] == "Outside Parking":
155
+ # High-Precision Partial Alignment check
156
+ best_slot = max(assign["slots"], key=lambda x: x["iou"]) if assign["slots"] else None
157
+ if best_slot and 0.05 < best_slot["iou"] < 0.5:
158
+ active_details.append({
159
+ "type": "PARTIAL ALIGNMENT",
160
+ "msg": f"Critical Alignment Failure | Slot {best_slot['id']}",
161
+ "level": "Alert",
162
+ "color": "#ef4444"
163
+ })
164
+ else:
165
+ active_details.append({
166
+ "type": "OUTSIDE PARKING",
167
+ "msg": "Vehicle parked in non-designated area (OUTSIDE PARKING)",
168
+ "level": "Alert",
169
+ "color": "#ef4444"
170
+ })
171
+
172
+ overlay = frame.copy()
173
+ cv2.rectangle(overlay, (10, 10), (250, 120), (0, 0, 0), -1)
174
+ cv2.addWeighted(overlay, 0.6, frame, 0.4, 0, frame)
175
+
176
+ cv2.putText(frame, f"TOTAL CARS: {counts['total']}", (20, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 2)
177
+ cv2.putText(frame, f"OUTSIDE: {counts['outside']}", (20, 65), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)
178
+ cv2.putText(frame, f"DOUBLE PK: {counts['double']}", (20, 90), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2)
179
+
180
+ return frame, counts, car_assignments, active_details
181
+
182
+ def main():
183
+ # Diagnostic Runner
184
+ import sys
185
+ video_source = sys.argv[1] if len(sys.argv) > 1 else 0 # Default to webcam
186
+
187
+ detector = WrongParkingDetector()
188
+ cap = cv2.VideoCapture(video_source)
189
+
190
+ print("[SYSTEM] Tactical Violation Monitor ACTIVE. Press 'q' to exit.")
191
+
192
+ while cap.isOpened():
193
+ success, frame = cap.read()
194
+ if not success: break
195
+
196
+ processed_frame, stats = detector.analyze_frame(frame)
197
+
198
+ cv2.imshow("NEXUS VIOLATION MONITOR", processed_frame)
199
+ if cv2.waitKey(1) & 0xFF == ord('q'): break
200
+
201
+ cap.release()
202
+ cv2.destroyAllWindows()
203
+
204
+ if __name__ == "__main__":
205
+ main()