Mathematicaljuice commited on
Commit
314b8df
·
verified ·
1 Parent(s): d639f3e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -6
app.py CHANGED
@@ -5,6 +5,9 @@ import torch
5
  import torch.nn as nn
6
  import gradio as gr
7
 
 
 
 
8
  GESTURE_LABELS = {
9
  0: "A", 1: "B", 2: "L", 3: "U", 4: "V", 5: "W",
10
  6: "Z", 7: "F", 8: "five", 9: "one", 10: "three",
@@ -15,6 +18,9 @@ GESTURE_LABELS = {
15
  }
16
  CONF_THRESHOLD = 0.6
17
 
 
 
 
18
  class GestureNet(nn.Module):
19
  def __init__(self, input_size=126, num_classes=len(GESTURE_LABELS)):
20
  super().__init__()
@@ -23,6 +29,7 @@ class GestureNet(nn.Module):
23
  self.fc3 = nn.Linear(128, num_classes)
24
  self.relu = nn.ReLU()
25
  self.dropout = nn.Dropout(0.3)
 
26
  def forward(self, x):
27
  x = self.relu(self.fc1(x))
28
  x = self.dropout(x)
@@ -34,13 +41,22 @@ model = GestureNet()
34
  model.load_state_dict(torch.load("gesture_model1.pth", map_location="cpu"))
35
  model.eval()
36
 
 
 
 
37
  mp_hands = mp.solutions.hands
38
 
 
 
 
39
  def predict(image):
40
- image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # Gradio sends RGB
41
- image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
 
 
42
  with mp_hands.Hands(static_image_mode=True, max_num_hands=2) as hands:
43
  results = hands.process(image_rgb)
 
44
  coords = []
45
  if results.multi_hand_landmarks:
46
  for hand_landmarks in results.multi_hand_landmarks:
@@ -50,26 +66,32 @@ def predict(image):
50
  if max_val > 0:
51
  hand_coords /= max_val
52
  coords.extend(hand_coords.flatten())
 
53
  if len(coords) < 126:
54
  coords.extend([0.0] * (126 - len(coords)))
55
  elif len(coords) > 126:
56
  coords = coords[:126]
 
57
  if len(coords) == 126:
58
  input_tensor = torch.tensor(coords, dtype=torch.float32).unsqueeze(0)
59
  with torch.no_grad():
60
  outputs = model(input_tensor)
61
- probs = torch.softmax(outputs, dim=1).numpy()[0]
62
- pred_class = np.argmax(probs)
63
- confidence = probs[pred_class]
64
  if confidence >= CONF_THRESHOLD:
65
  return f"{GESTURE_LABELS[pred_class]} ({confidence*100:.2f}%)"
 
66
  return "Unknown"
67
 
 
 
 
68
  app = gr.Interface(
69
  fn=predict,
70
  inputs=gr.Image(type="numpy"),
71
  outputs="text",
72
  title="Hand Gesture Recognition",
73
- description="Upload an image of a hand gesture"
74
  )
75
  app.launch()
 
5
  import torch.nn as nn
6
  import gradio as gr
7
 
8
+ # ----------------------------
9
+ # Labels
10
+ # ----------------------------
11
  GESTURE_LABELS = {
12
  0: "A", 1: "B", 2: "L", 3: "U", 4: "V", 5: "W",
13
  6: "Z", 7: "F", 8: "five", 9: "one", 10: "three",
 
18
  }
19
  CONF_THRESHOLD = 0.6
20
 
21
+ # ----------------------------
22
+ # Model
23
+ # ----------------------------
24
  class GestureNet(nn.Module):
25
  def __init__(self, input_size=126, num_classes=len(GESTURE_LABELS)):
26
  super().__init__()
 
29
  self.fc3 = nn.Linear(128, num_classes)
30
  self.relu = nn.ReLU()
31
  self.dropout = nn.Dropout(0.3)
32
+
33
  def forward(self, x):
34
  x = self.relu(self.fc1(x))
35
  x = self.dropout(x)
 
41
  model.load_state_dict(torch.load("gesture_model1.pth", map_location="cpu"))
42
  model.eval()
43
 
44
+ # ----------------------------
45
+ # MediaPipe
46
+ # ----------------------------
47
  mp_hands = mp.solutions.hands
48
 
49
+ # ----------------------------
50
+ # Predict
51
+ # ----------------------------
52
  def predict(image):
53
+ # Gradio sends RGB, convert to BGR for OpenCV then back to RGB for MediaPipe
54
+ image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
55
+ image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
56
+
57
  with mp_hands.Hands(static_image_mode=True, max_num_hands=2) as hands:
58
  results = hands.process(image_rgb)
59
+
60
  coords = []
61
  if results.multi_hand_landmarks:
62
  for hand_landmarks in results.multi_hand_landmarks:
 
66
  if max_val > 0:
67
  hand_coords /= max_val
68
  coords.extend(hand_coords.flatten())
69
+
70
  if len(coords) < 126:
71
  coords.extend([0.0] * (126 - len(coords)))
72
  elif len(coords) > 126:
73
  coords = coords[:126]
74
+
75
  if len(coords) == 126:
76
  input_tensor = torch.tensor(coords, dtype=torch.float32).unsqueeze(0)
77
  with torch.no_grad():
78
  outputs = model(input_tensor)
79
+ probs = torch.softmax(outputs, dim=1)
80
+ pred_class = torch.argmax(probs, dim=1).item()
81
+ confidence = probs[0][pred_class].item()
82
  if confidence >= CONF_THRESHOLD:
83
  return f"{GESTURE_LABELS[pred_class]} ({confidence*100:.2f}%)"
84
+
85
  return "Unknown"
86
 
87
+ # ----------------------------
88
+ # Gradio UI
89
+ # ----------------------------
90
  app = gr.Interface(
91
  fn=predict,
92
  inputs=gr.Image(type="numpy"),
93
  outputs="text",
94
  title="Hand Gesture Recognition",
95
+ description="Upload an image of a hand gesture to recognize it."
96
  )
97
  app.launch()