-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
148 lines (120 loc) · 4.13 KB
/
Copy pathmain.py
File metadata and controls
148 lines (120 loc) · 4.13 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
"""Main script for real-time sign language detection."""
import cv2
import argparse
from pathlib import Path
from src.utils.config_loader import ConfigLoader
from src.models.model_loader import TFLiteModel
from src.preprocessing.image_processor import ImageProcessor
from src.inference.predictor import SignLanguagePredictor
def main(config_path: str = "configs/config.yaml"):
"""
Run real-time sign language detection.
Args:
config_path: Path to configuration file
"""
# Load configuration
config = ConfigLoader(config_path)
# Load labels
labels_file = config.get('data.labels_file', 'data/labels.txt')
labels = load_labels(labels_file)
if not labels:
print("Warning: No labels found. Please create data/labels.txt")
return
# Initialize model
model_path = config.get('model.path')
if not Path(model_path).exists():
print(f"Error: Model not found at {model_path}")
print("Please train or download a model first.")
return
print(f"Loading model from {model_path}...")
model = TFLiteModel(model_path)
# Initialize preprocessor
input_size = tuple(config.get('model.input_size', [224, 224]))
processor = ImageProcessor(
target_size=input_size,
normalize=config.get('preprocessing.normalize', True),
mean=config.get('preprocessing.mean'),
std=config.get('preprocessing.std')
)
# Initialize predictor
predictor = SignLanguagePredictor(
model=model,
processor=processor,
labels=labels,
buffer_size=config.get('inference.buffer_size', 5),
confidence_threshold=config.get('model.confidence_threshold', 0.7)
)
# Initialize camera
camera_resolution = config.get('camera.resolution', [640, 480])
camera_fps = config.get('camera.fps', 30)
print("Initializing camera...")
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, camera_resolution[0])
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, camera_resolution[1])
cap.set(cv2.CAP_PROP_FPS, camera_fps)
if not cap.isOpened():
print("Error: Cannot open camera")
return
print("Starting real-time detection... Press 'q' to quit, 'r' to reset buffer")
try:
while True:
ret, frame = cap.read()
if not ret:
print("Error: Cannot read frame")
break
# Predict
label, confidence = predictor.predict(frame)
# Display results
display_frame = frame.copy()
# Draw prediction text
text = f"{label}: {confidence:.2f}"
cv2.putText(
display_frame,
text,
(10, 30),
cv2.FONT_HERSHEY_SIMPLEX,
1.0,
(0, 255, 0) if confidence > 0.7 else (0, 255, 255),
2
)
# Draw FPS
fps_text = f"FPS: {predictor.get_fps():.1f}"
cv2.putText(
display_frame,
fps_text,
(10, 70),
cv2.FONT_HERSHEY_SIMPLEX,
0.7,
(255, 255, 255),
2
)
# Show frame
cv2.imshow('Sign Language Detection', display_frame)
# Handle key presses
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
break
elif key == ord('r'):
predictor.reset_buffer()
print("Buffer reset")
finally:
cap.release()
cv2.destroyAllWindows()
print("Stopped.")
def load_labels(labels_file: str) -> list:
"""Load labels from file."""
labels_path = Path(labels_file)
if not labels_path.exists():
return []
with open(labels_path, 'r') as f:
return [line.strip() for line in f if line.strip()]
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Sign Language Detection")
parser.add_argument(
"--config",
type=str,
default="configs/config.yaml",
help="Path to config file"
)
args = parser.parse_args()
main(args.config)