Spaces:
Sleeping
Sleeping
Upload 7 files
Browse filesFiles changed (7)
- app.pyAdded+77
- asl_model.h5Added+3
- gesture_data.csvAdded
- gesture_recognition.pyAdded+42
- requirements.txtAdded+5
- templates/index.htmlAdded+21
- train_model.pyAdded+37
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677from flask import Flask, render_template, Response
import cv2
import numpy as np
import tensorflow as tf
import mediapipe as mp
app = Flask(__name__)
@app.route('/test')
def test():
return "Flask is working!"
# Load the trained model
model = tf.keras.models.load_model("asl_model.h5")
# Initialize MediaPipe for hand tracking
mp_hands = mp.solutions.hands
mp_drawing = mp.solutions.drawing_utils
hands = mp_hands.Hands()
cap = cv2.VideoCapture(0)
# Define gesture labels (must match training labels)
gesture_labels = ["A", "B", "C", "D", "E"] # Update based on your dataset
def predict_gesture(landmarks):
""" Predicts gesture based on hand landmarks. """
landmarks = np.array(landmarks).reshape(1, -1) # Reshape for model
prediction = model.predict(landmarks)
return gesture_labels[np.argmax(prediction)] # Get the highest probability gesture
def generate_frames():
""" Captures video frames and processes hand gestures in real-time. """
while True:
ret, frame = cap.read()
if not ret:
break
frame = cv2.flip(frame, 1)
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = hands.process(rgb_frame)
detected_gesture = "None"
if results.multi_hand_landmarks:
for hand_landmarks in results.multi_hand_landmarks:
mp_drawing.draw_landmarks(frame, hand_landmarks, mp_hands.HAND_CONNECTIONS)
# Extract landmark positions
landmarks = []
for lm in hand_landmarks.landmark:
landmarks.extend([lm.x, lm.y, lm.z])
detected_gesture = predict_gesture(landmarks)
# Display detected gesture
cv2.putText(frame, f"Gesture: {detected_gesture}", (50, 50),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2, cv2.LINE_AA)
_, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
@app.route('/')
def index():
return render_template('index.html')
@app.route('/video')
def video():
return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(debug=True)
123version https://git-lfs.github.com/spec/v1oid sha256:b7b6edc86eb0df4e2c94bf8c361eeb23532e0496dfb4b43518d1277c114ef54asize 227568123456789101112131415161718192021222324252627282930313233343536373839404142import cv2
import mediapipe as mp
import numpy as np
import csv
mp_hands = mp.solutions.hands
mp_drawing = mp.solutions.drawing_utils
hands = mp_hands.Hands()
cap = cv2.VideoCapture(0)
gesture_name = input("Enter gesture name: ") # Type 'A', 'B', etc.
with open("gesture_data.csv", "a", newline="") as f:
writer = csv.writer(f)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
frame = cv2.flip(frame, 1)
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = hands.process(rgb_frame)
if results.multi_hand_landmarks:
for hand_landmarks in results.multi_hand_landmarks:
mp_drawing.draw_landmarks(frame, hand_landmarks, mp_hands.HAND_CONNECTIONS)
landmarks = []
for lm in hand_landmarks.landmark:
landmarks.extend([lm.x, lm.y, lm.z])
landmarks.append(gesture_name) # Add label to the data
writer.writerow(landmarks)
cv2.imshow("Collecting Data", frame)
if cv2.waitKey(1) & 0xFF == ord('q'): # Press 'q' to stop
break
cap.release()
cv2.destroyAllWindows()12345flask
opencv-python
mediapipe
tensorflow
numpy123456789101112131415161718192021<html>
<head>
<title>ASL Hand Gesture Recognition</title>
</head>
<body>
<h1>ASL Hand Gesture Recognition</h1>
<img src="{{ url_for('video') }}" width="640" height="480">
<h2>Detected Gesture: <span id="gesture">None</span></h2>
<script>
setInterval(async () => {
let response = await fetch('/video');
let text = await response.text();
let match = text.match(/Gesture: (\w+)/);
if (match) {
document.getElementById('gesture').innerText = match[1];
}
}, 1000);
</script>
</body>
</html>12345678910111213141516171819202122232425262728293031323334353637import pandas as pd
import numpy as np
import tensorflow as tf
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# Load the dataset
data = pd.read_csv("gesture_data.csv")
# Split features (X) and labels (y)
X = data.iloc[:, :-1].values # Hand landmark positions
y = data.iloc[:, -1] # Gesture labels
# Convert labels to numbers
from sklearn.preprocessing import LabelEncoder
encoder = LabelEncoder()
y = encoder.fit_transform(y)
# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Build the model
model = Sequential([
Dense(128, activation='relu', input_shape=(X.shape[1],)),
Dense(64, activation='relu'),
Dense(len(set(y)), activation='softmax') # Number of gesture classes
])
# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Train the model
model.fit(X_train, y_train, epochs=20, validation_data=(X_test, y_test))
# Save the trained model
model.save("asl_model.h5")app.pyAdded+77
asl_model.h5Added+3
gesture_data.csvAdded
gesture_recognition.pyAdded+42
requirements.txtAdded+5
templates/index.htmlAdded+21
train_model.pyAdded+37