Ramadhan2310 commited on
Commit
76245f5
·
verified ·
1 Parent(s): e3029f1

Update myapp/detector.py

Browse files
Files changed (1) hide show
  1. myapp/detector.py +131 -90
myapp/detector.py CHANGED
@@ -1,90 +1,131 @@
1
- import cv2
2
- import os
3
- import time
4
- import numpy as np
5
- from ultralytics import YOLO
6
- from django.conf import settings
7
-
8
- class TrafficDetector:
9
- def __init__(self, model_rel_path):
10
- self.model_path = os.path.join(settings.MEDIA_ROOT, model_rel_path)
11
- self.model = YOLO(self.model_path)
12
- self.objects_count = 0 # Store current vehicle count
13
- self.current_file_id = None # Track currently processing file
14
- self.stop_processing = False # Flag to stop processing
15
-
16
- def process_file(self, file_path):
17
- ext = os.path.splitext(file_path)[1].lower()
18
-
19
- if ext in ['.jpg', '.jpeg', '.png', '.bmp']:
20
- return self.process_image(file_path)
21
- elif ext in ['.mp4', '.avi', '.mov', '.mkv']:
22
- return self.get_frames(file_path)
23
- else:
24
- return None
25
-
26
- def process_image(self, image_path):
27
- frame = cv2.imread(image_path)
28
- if frame is None:
29
- return
30
-
31
- results = self.model.predict(frame, conf=0.5, verbose=False)
32
- annotated_frame = results[0].plot()
33
-
34
- _, buffer = cv2.imencode('.jpg', annotated_frame)
35
- yield (b'--frame\r\n'
36
- b'Content-Type: image/jpeg\r\n\r\n' + buffer.tobytes() + b'\r\n')
37
-
38
- def get_frames(self, video_path):
39
- current_timer = 10 # Start with 10 seconds
40
- last_time_update = time.time()
41
- lampu_state = "GREEN" # Start with GREEN
42
- objects_count = 0
43
-
44
-
45
- cap = cv2.VideoCapture(video_path)
46
- while cap.isOpened():
47
- # Check if stop processing flag is set
48
- if self.stop_processing:
49
- break
50
-
51
- ret, frame = cap.read()
52
- if not ret: break
53
-
54
- results = self.model.predict(frame, conf=0.5, verbose=False)
55
- frame = results[0].plot()
56
-
57
- for r in results:
58
- boxes = r.boxes.cpu().numpy()
59
- self.objects_count = len(boxes)
60
-
61
- if time.time() - last_time_update >= 1:
62
- if current_timer > 0:
63
- current_timer -= 1
64
- last_time_update = time.time()
65
-
66
- if current_timer <= 0:
67
- if lampu_state == "RED":
68
- # Switch to GREEN
69
- lampu_state = "GREEN"
70
- # If it's quiet, keep green short. If busy, green stays longer to clear traffic.
71
- current_timer = 20 if self.objects_count > 20 else 10
72
-
73
- else: # If currently GREEN
74
- # Switch to RED
75
- lampu_state = "RED"
76
- # If busy, red stays longer to manage other lanes (simulated).
77
- current_timer = 30 if self.objects_count > 20 else 15
78
-
79
- color_map = {"RED": (0, 0, 255), "GREEN": (0, 255, 0)}
80
- current_color = color_map[lampu_state]
81
-
82
- cv2.putText(frame, f"STATUS: {lampu_state}", (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, current_color, 3)
83
- cv2.putText(frame, f"TIMER: {current_timer}s", (20, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
84
- cv2.putText(frame, f"VEHICLES: {self.objects_count}", (20, 150), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
85
-
86
- _, buffer = cv2.imencode('.jpg', frame)
87
- yield (b'--frame\r\n'
88
- b'Content-Type: image/jpeg\r\n\r\n' + buffer.tobytes() + b'\r\n')
89
- cap.release()
90
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import os
3
+ import time
4
+ import numpy as np
5
+ from ultralytics import YOLO
6
+ from django.conf import settings
7
+
8
+ class TrafficDetector:
9
+ def __init__(self, model_rel_path):
10
+ self.model_path = os.path.join(settings.MEDIA_ROOT, model_rel_path)
11
+ self.model = YOLO(self.model_path)
12
+ self.objects_count = 0
13
+ self.traffic_weight = 0
14
+ self.current_file_id = None
15
+ self.stop_processing = False
16
+
17
+ def process_file(self, file_path):
18
+ ext = os.path.splitext(file_path)[1].lower()
19
+
20
+ if ext in ['.jpg', '.jpeg', '.png', '.bmp']:
21
+ return self.process_image(file_path)
22
+ elif ext in ['.mp4', '.avi', '.mov', '.mkv']:
23
+ return self.get_frames(file_path)
24
+ else:
25
+ return None
26
+
27
+ def process_image(self, image_path):
28
+ frame = cv2.imread(image_path)
29
+ if frame is None:
30
+ return
31
+
32
+ objects_count = 0
33
+ traffic_weight = 0
34
+
35
+ results = self.model.predict(frame, conf=0.5, verbose=False)
36
+ frame = results[0].plot()
37
+
38
+ for r in results:
39
+ boxes = r.boxes
40
+ objects_count = len(boxes)
41
+ for box in boxes:
42
+ cls_id = int(box.cls[0])
43
+ label = r.names[cls_id]
44
+
45
+ if label.lower() == 'mobil':
46
+ traffic_weight += 4
47
+ elif label.lower() == 'kendaraan besar':
48
+ traffic_weight += 6
49
+ else:
50
+ traffic_weight += 1
51
+
52
+ if traffic_weight > 100:
53
+ traffic_weight = 100
54
+
55
+ self.traffic_weight = traffic_weight
56
+ self.objects_count = objects_count
57
+
58
+
59
+ _, buffer = cv2.imencode('.jpg', frame)
60
+ yield (b'--frame\r\n'
61
+ b'Content-Type: image/jpeg\r\n\r\n' + buffer.tobytes() + b'\r\n')
62
+
63
+ def get_frames(self, video_path):
64
+ current_timer = 10
65
+ last_time_update = time.time()
66
+ lampu_state = "GREEN"
67
+ objects_count = 0
68
+
69
+
70
+ cap = cv2.VideoCapture(video_path)
71
+ while cap.isOpened():
72
+ if self.stop_processing:
73
+ break
74
+
75
+ ret, frame = cap.read()
76
+ if not ret: break
77
+
78
+ try:
79
+ results = self.model.predict(frame, conf=0.5, verbose=False)
80
+ frame = results[0].plot()
81
+
82
+ traffic_weight = 0
83
+ objects_count = 0
84
+ for r in results:
85
+ boxes = r.boxes
86
+ objects_count += len(boxes)
87
+ for box in boxes:
88
+ cls_id = int(box.cls[0])
89
+ label = r.names[cls_id]
90
+
91
+ if label.lower() == 'mobil':
92
+ traffic_weight += 4
93
+ elif label.lower() == 'kendaraan besar':
94
+ traffic_weight += 6
95
+ else:
96
+ traffic_weight += 1
97
+
98
+ if traffic_weight > 100:
99
+ traffic_weight = 100
100
+
101
+ self.traffic_weight = traffic_weight
102
+ self.objects_count = objects_count
103
+
104
+ if time.time() - last_time_update >= 1:
105
+ if current_timer > 0:
106
+ current_timer -= 1
107
+ last_time_update = time.time()
108
+
109
+ if current_timer <= 0:
110
+ if lampu_state == "RED":
111
+ lampu_state = "GREEN"
112
+ current_timer = 20 if self.traffic_weight > 80 else 10
113
+ else:
114
+ lampu_state = "RED"
115
+ current_timer = 30 if self.traffic_weight > 80 else 15
116
+
117
+ color_map = {"RED": (0, 0, 255), "GREEN": (0, 255, 0)}
118
+ current_color = color_map[lampu_state]
119
+
120
+ cv2.putText(frame, f"STATUS: {lampu_state}", (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, current_color, 3)
121
+ cv2.putText(frame, f"TIMER: {current_timer}s", (20, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
122
+
123
+ _, buffer = cv2.imencode('.jpg', frame)
124
+ yield (b'--frame\r\n'
125
+ b'Content-Type: image/jpeg\r\n\r\n' + buffer.tobytes() + b'\r\n')
126
+
127
+ except Exception as e:
128
+ print(f"Error processing frame: {e}")
129
+ continue
130
+
131
+ cap.release()