-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathegg_testing.py
More file actions
238 lines (184 loc) · 7.66 KB
/
Copy pathegg_testing.py
File metadata and controls
238 lines (184 loc) · 7.66 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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#!/usr/bin/env python3
"""
Egg Detection Preview - Browser Stream
Open http://<arduino-ip>:8081 in your browser
"""
import time
import cv2
import numpy as np
from http.server import HTTPServer, BaseHTTPRequestHandler
from threading import Thread
print("\n" + "="*50)
print(" EGG DETECTION PREVIEW")
print(" Browser Stream Version")
print("="*50 + "\n")
# ===== CONFIGURATION =====
CAMERA_DEVICE = '/dev/video-eggs'
MODEL_PATH = 'best_eggs.onnx'
DETECTION_CONFIDENCE = 0.5
STREAM_PORT = 8081
CLASSES = {0: 'egg'}
BOX_COLOR = (0, 255, 255)
TEXT_COLOR = (0, 0, 0)
current_frame = None
class YOLODetector:
def __init__(self, model_path, classes_dict):
self.classes = classes_dict
try:
self.net = cv2.dnn.readNetFromONNX(model_path)
self.net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)
self.net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)
self.img_size = 320
self.enabled = True
print(f"[DETECTOR] ✓ Model loaded: {model_path}")
except Exception as e:
print(f"[DETECTOR] ✗ Failed: {e}")
self.enabled = False
def detect(self, frame):
if not self.enabled:
return []
try:
orig_h, orig_w = frame.shape[:2]
blob = cv2.dnn.blobFromImage(
frame, 1/255.0, (self.img_size, self.img_size),
swapRB=True, crop=False
)
self.net.setInput(blob)
outputs = self.net.forward()
predictions = outputs[0].T
scale_x = orig_w / self.img_size
scale_y = orig_h / self.img_size
detections = []
for pred in predictions:
x_center, y_center, w, h = pred[:4]
class_scores = pred[4:]
class_id = np.argmax(class_scores)
confidence = class_scores[class_id]
if confidence > DETECTION_CONFIDENCE:
x1 = int((x_center - w/2) * scale_x)
y1 = int((y_center - h/2) * scale_y)
x2 = int((x_center + w/2) * scale_x)
y2 = int((y_center + h/2) * scale_y)
x1, y1 = max(0, x1), max(0, y1)
x2, y2 = min(orig_w, x2), min(orig_h, y2)
detections.append({
'class_name': self.classes.get(class_id, f'Class_{class_id}'),
'confidence': float(confidence),
'bbox': (x1, y1, x2, y2)
})
if detections:
boxes = [d['bbox'] for d in detections]
scores = [d['confidence'] for d in detections]
indices = cv2.dnn.NMSBoxes(boxes, scores, DETECTION_CONFIDENCE, 0.5)
if len(indices) > 0:
detections = [detections[i] for i in indices.flatten()]
return detections
except Exception as e:
print(f"[DETECTOR] Error: {e}")
return []
def draw_boxes(frame, detections):
for det in detections:
x1, y1, x2, y2 = det['bbox']
label = f"{det['class_name']}: {det['confidence']:.0%}"
cv2.rectangle(frame, (x1, y1), (x2, y2), BOX_COLOR, 2)
(text_w, text_h), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.6, 2)
cv2.rectangle(frame, (x1, y1 - text_h - 10), (x1 + text_w + 6, y1), BOX_COLOR, -1)
cv2.putText(frame, label, (x1 + 3, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.6, TEXT_COLOR, 2)
return frame
class StreamHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b'''
<html><head><title>Egg Detection</title></head>
<body style="margin:0;background:#000;display:flex;justify-content:center;align-items:center;height:100vh;">
<img src="/stream" style="max-width:100%;max-height:100%;">
</body></html>
''')
elif self.path == '/stream':
self.send_response(200)
self.send_header('Content-type', 'multipart/x-mixed-replace; boundary=frame')
self.end_headers()
while True:
if current_frame is not None:
try:
_, jpeg = cv2.imencode('.jpg', current_frame, [cv2.IMWRITE_JPEG_QUALITY, 80])
self.wfile.write(b'--frame\r\n')
self.wfile.write(b'Content-Type: image/jpeg\r\n\r\n')
self.wfile.write(jpeg.tobytes())
self.wfile.write(b'\r\n')
except:
break
time.sleep(0.03)
def log_message(self, format, *args):
pass
def camera_loop(detector):
global current_frame
print(f"[CAMERA] Opening {CAMERA_DEVICE}...")
cap = cv2.VideoCapture(CAMERA_DEVICE, cv2.CAP_V4L2)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M','J','P','G'))
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
if not cap.isOpened():
print("[CAMERA] ✗ Failed to open camera")
return
print("[CAMERA] ✓ Camera opened")
frame_count = 0
fps_time = time.time()
fps = 0
egg_count = 0
fail_count = 0
try:
while True:
ret, frame = cap.read()
if not ret:
fail_count += 1
if fail_count % 100 == 0:
print(f"[CAMERA] ⚠ Frame read failed {fail_count} times")
time.sleep(0.01)
continue
fail_count = 0
frame_count += 1
# Debug: print every 30 frames
if frame_count % 30 == 0:
fps = 30 / (time.time() - fps_time)
fps_time = time.time()
print(f"[CAMERA] Frame {frame_count} | {fps:.1f} FPS")
detections = detector.detect(frame)
if detections:
frame = draw_boxes(frame, detections)
if len(detections) != egg_count:
egg_count = len(detections)
print(f"[DETECTED] 🥚 {egg_count} egg(s)")
else:
if egg_count != 0:
egg_count = 0
#cv2.putText(frame, f"Eggs: {len(detections)} | FPS: {fps:.1f}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
current_frame = frame.copy()
time.sleep(0.03)
except Exception as e:
print(f"[CAMERA] ✗ Error: {e}")
finally:
cap.release()
print("[CAMERA] Released")
def main():
detector = YOLODetector(MODEL_PATH, CLASSES)
# Start camera thread
cam_thread = Thread(target=camera_loop, args=(detector,), daemon=True)
cam_thread.start()
# Wait a moment for camera to start
time.sleep(2)
if current_frame is None:
print("[WARNING] No frames yet - camera may be stuck")
server = HTTPServer(('0.0.0.0', STREAM_PORT), StreamHandler)
print(f"[STREAM] Open in browser: http://<arduino-ip>:{STREAM_PORT}")
print("[STREAM] Press Ctrl+C to stop\n")
try:
server.serve_forever()
except KeyboardInterrupt:
print("\n[STREAM] Stopped")
if __name__ == "__main__":
main()