-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
181 lines (141 loc) · 5.34 KB
/
main.py
File metadata and controls
181 lines (141 loc) · 5.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import time
import logging
import math
import queue
import threading
import cv2
import cvzone
import requests
import yaml
from ultralytics import YOLO
with open('config.yaml', 'r') as f:
config = yaml.safe_load(f)
video_path = config['video_path']
model_path = config['model']['path']
model = YOLO(model_path)
classNames = config['classNames']
class_count = ["box"]
NUM_WORKER_THREADS = 100
FRAME_SKIP_INTERVAL = 10
stop_thread = False
# Logging configuration
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("app.log"),
logging.StreamHandler()
])
def measure_runtime(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
runtime = end_time - start_time
print(f"Runtime of {func.__name__}: {runtime} seconds")
return result
return wrapper
input_frame_queue = queue.Queue(maxsize=NUM_WORKER_THREADS * 2)
processed_queue = queue.Queue(maxsize=NUM_WORKER_THREADS * 2)
detections_queue = queue.Queue(maxsize=NUM_WORKER_THREADS * 2)
detect_action_queue = queue.Queue(maxsize=NUM_WORKER_THREADS * 2)
@measure_runtime
def detect_objects(frame):
results = model(frame, stream=True)
for r in results:
boxes = r.boxes
for box in boxes:
cls = int(box.cls[0])
conf = math.ceil((box.conf[0] * 100)) / 100
current_class = classNames[cls]
if current_class in class_count:
detections_queue.put({'class': current_class, 'conf': conf, 'coord': box})
def process_frame(frame):
print("Start individual threads for model detection: Frames")
detections_thread1 = threading.Thread(target=detect_objects, args=(frame,))
detections_thread1.start()
detections_thread1.join()
while not detections_queue.empty():
detection_marking = detections_queue.get()
class_label = detection_marking["class"]
conf = detection_marking["conf"]
x1, y1, x2, y2 = detection_marking['coord'].xyxy[0]
x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
Length = x2 - x1
width = y2 - y1
Length = Length / 58.7
Length = round(Length, 2)
width = width / 58.7
width = round(width, 2)
text = f"Length: {Length} cm, width: {width} cm"
position = (max(0, x1), max(10, y1 - 10))
# D = round(D, 2)
# cvzone.putTextRect(frame, f"{D} mm", (max(0, x1), max(10, y1)),
# thickness=3, offset=2)
# cvzone.putTextRect(frame, text, position, thickness=3, offset=2)
# cv2.rectangle(frame, (x1, y1), (x2, y2), (255, 0, 255), 4)
detection_marker = True
# if detection_marker:
# detect_action_queue.put({'frame': frame.copy(), 'class': class_label, 'conf': conf})
# detections_queue.queue.clear()
print("detections_queue 3 " + str(detections_queue.qsize()))
print("Processed individual frame.")
return frame
def capture_frames(rtsp_url):
cap = cv2.VideoCapture(rtsp_url)
#cap = cv2.VideoCapture(0)
frame_count = 0
while not stop_thread:
ret, frame = cap.read()
if not ret:
break
if frame_count % FRAME_SKIP_INTERVAL == 0:
input_frame_queue.put(frame)
frame_count += 1
def process_frames():
while not stop_thread:
if not input_frame_queue.empty():
print(f'input_frame_queue size: {input_frame_queue.qsize()}')
input_frame = input_frame_queue.get()
processed_frame = process_frame(input_frame)
processed_queue.put(processed_frame if processed_frame is not None else input_frame)
print(f'Exiting method process_frames()')
def display_frames():
global stop_thread
while not stop_thread:
processed_frame = processed_queue.get()
print(f'Process Queue size{processed_queue.qsize()}')
width = 640
height = 480
resized_frame = cv2.resize(processed_frame, (width, height))
# cv2.imshow('Processed Frame', resized_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
stop_thread = True
break
cv2.destroyAllWindows()
if __name__ == "__main__":
try:
rtsp_url = "http://192.168.1.25:8080/video"
capture_thread = threading.Thread(target=capture_frames, args=(rtsp_url,))
capture_thread.start()
process_thread = threading.Thread(target=process_frames, )
process_thread.start()
display_thread = threading.Thread(target=display_frames, )
display_thread.start()
all_threads = [capture_thread, process_thread, display_thread]
for t in all_threads:
t.start()
print(f'Starting Thread {t.name} ...')
for t in all_threads:
print(f'Awaiting Thread {t.name} ...')
t.join()
print(f'Completion Thread {t.name} ...')
except Exception as e:
print(e)
finally:
while not input_frame_queue.empty():
input_frame_queue.get()
while not detections_queue.empty():
detections_queue.get()
while not processed_queue.empty():
processed_queue.get()
print("Exiting Application")