-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcamera.py
More file actions
78 lines (63 loc) · 2.16 KB
/
Copy pathcamera.py
File metadata and controls
78 lines (63 loc) · 2.16 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
import cv2
import numpy as np
import tflite_runtime.interpreter as tflite
import time
import move # Your move.py must define movement functions
# Load model and labels
MODEL_PATH = "detect.tflite"
LABELS_PATH = "labels.txt"
interpreter = tflite.Interpreter(model_path=MODEL_PATH)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
with open(LABELS_PATH, "r") as f:
labels = [line.strip() for line in f.readlines()]
def preprocess(frame):
input_shape = input_details[0]['shape']
resized = cv2.resize(frame, (input_shape[2], input_shape[1]))
normalized = resized / 255.0
return np.expand_dims(normalized.astype(np.float32), axis=0)
def detect_objects(frame):
input_data = preprocess(frame)
interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])[0]
return output_data
def respond_to_detection(results):
for i, score in enumerate(results):
if score > 0.6:
label = labels[i]
print(f"Detected: {label} ({score:.2f})")
# Example: move based on object
if label == "person":
move.stop()
elif label == "cat":
move.turn_left()
elif label == "dog":
move.turn_right()
elif label == "bottle":
move.move_forward()
return # Act on first confident detection
def main():
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("❌ Camera not accessible")
return
print("📷 Starting camera. Press 'q' to quit.")
try:
while True:
ret, frame = cap.read()
if not ret:
break
results = detect_objects(frame)
respond_to_detection(results)
cv2.imshow("Camera Feed", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
finally:
cap.release()
cv2.destroyAllWindows()
move.stop()
print("🛑 Camera stopped and robot halted.")
if __name__ == "__main__":
main()