CantonMonkey commited on
Commit
4db3489
·
1 Parent(s): 4763b27

add app files

Browse files
Files changed (5) hide show
  1. Classifier_ASL.py +37 -0
  2. Hand_Tracking_ASL.py +58 -0
  3. best_model.h5 +3 -0
  4. data preprocessing.py +123 -0
  5. main_ASL.py +66 -0
Classifier_ASL.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from tensorflow import keras
2
+ import numpy as np
3
+ import cv2
4
+ import tensorflow as tf
5
+
6
+
7
+ class Classifier:
8
+ def __init__(self, modelPath):
9
+ self.model=tf.keras.models.load_model(modelPath)
10
+ self.imageSize=64
11
+
12
+ def get_prediction(self, imgCrop, hand):
13
+ # img input
14
+ imgResize=cv2.resize(imgCrop, (self.imageSize, self.imageSize))
15
+ img_normalized=imgResize/255.0
16
+ img_reshaped=np.reshape(img_normalized, (1, self.imageSize, self.imageSize, 3))
17
+
18
+ # coor input
19
+ landmarks=[]
20
+ for lm in hand["lmList"]:
21
+ coords=[lm[0]/64, lm[1]/64] # img size = 64*64, coor normalization
22
+ landmarks.extend(coords)
23
+ landmarks=np.array(landmarks).reshape(1, -1) # reshape as (1, 42)
24
+
25
+ # prediction by trained model
26
+ prediction=self.model.predict([img_reshaped, landmarks])
27
+ index=np.argmax(prediction)
28
+ probability=prediction[0][index]
29
+
30
+ labels={0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G', 7: 'H', 8: 'I', 9: 'J',
31
+ 10: 'K', 11: 'L', 12: 'M', 13: 'N', 14: 'O', 15: 'P', 16: 'Q', 17: 'R', 18: 'S',
32
+ 19: 'T', 20: 'U', 21: 'V', 22: 'W', 23: 'X', 24: 'Y', 25: 'Z', 26: 'del', 27: 'space'}
33
+
34
+ return labels[index], probability
35
+
36
+
37
+
Hand_Tracking_ASL.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import mediapipe as mp
3
+
4
+ class HandDetector:
5
+ def __init__(self, mode=False, maxHands=2, detectionCon=0.5, minTrackCon=0.5):
6
+ self.mode = mode
7
+ self.maxHands = maxHands
8
+ self.detectionCon = detectionCon
9
+ self.minTrackCon = minTrackCon
10
+
11
+ self.mpHands = mp.solutions.hands
12
+ self.hands = self.mpHands.Hands(static_image_mode=self.mode, max_num_hands=self.maxHands,
13
+ min_detection_confidence=self.detectionCon,
14
+ min_tracking_confidence=self.minTrackCon)
15
+ self.mpDraw = mp.solutions.drawing_utils
16
+ self.lmList = []
17
+
18
+ def findHands(self, img, draw=True, flipType=True):
19
+ imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
20
+ self.results = self.hands.process(imgRGB)
21
+ Hand = []
22
+ h, w, c = img.shape
23
+ if self.results.multi_hand_landmarks:
24
+ for handType, handLms in zip(self.results.multi_handedness, self.results.multi_hand_landmarks):
25
+ myHand = {}
26
+ ## lmList
27
+ mylmList = []
28
+ xList = []
29
+ yList = []
30
+ for id, lm in enumerate(handLms.landmark):
31
+ px, py, pz = int(lm.x * w), int(lm.y * h), int(lm.z * w)
32
+ # px, py, pz = lm.x, lm.y, lm.z
33
+ mylmList.append([px, py, pz])
34
+ xList.append(px)
35
+ yList.append(py)
36
+
37
+ ## bbox
38
+ xmin, xmax = min(xList), max(xList)
39
+ ymin, ymax = min(yList), max(yList)
40
+ boxW, boxH = xmax - xmin, ymax - ymin
41
+ bbox = xmin, ymin, boxW, boxH
42
+
43
+ myHand["lmList"] = mylmList
44
+ myHand["bbox"] = bbox
45
+
46
+ if flipType:
47
+ if handType.classification[0].label == "Right":
48
+ myHand["type"] = "Left"
49
+ else:
50
+ myHand["type"] = "Right"
51
+ else:
52
+ myHand["type"] = handType.classification[0].label
53
+ Hand.append(myHand)
54
+
55
+ if draw:
56
+ return Hand, img
57
+ else:
58
+ return Hand
best_model.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5de1e65ad467a8e09330d407003c7a621f63861594cb3a4480d9374f68041de0
3
+ size 132383960
data preprocessing.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import mediapipe as mp
3
+ import numpy as np
4
+ import os
5
+ import random
6
+ from tqdm import tqdm
7
+ import shutil
8
+
9
+
10
+ class HandProcessor:
11
+ def __init__(self, min_detection_confidence=0.8, min_tracking_confidence=0.5):
12
+ self.mpHands=mp.solutions.hands
13
+ self.hands=self.mpHands.Hands(
14
+ min_detection_confidence=min_detection_confidence,
15
+ min_tracking_confidence=min_tracking_confidence
16
+ )
17
+ self.offset=10
18
+ self.max_images_per_class=1400 # 1400 img for each class
19
+
20
+ def get_bbox_coordinates(self, results, image_shape):
21
+ """Get bounding box coordinates for a hand landmark."""
22
+ all_x, all_y=[], []
23
+ if results.multi_hand_landmarks:
24
+ for handLms in results.multi_hand_landmarks[0].landmark:
25
+ all_x.append(int(handLms.x*image_shape[1]))
26
+ all_y.append(int(handLms.y*image_shape[0]))
27
+
28
+ if all_x and all_y:
29
+ return min(all_x), min(all_y), max(all_x), max(all_y)
30
+ return None
31
+
32
+ def extract_landmarks(self, results):
33
+ """Extract normalized landmarks from detection results."""
34
+ if results.multi_hand_landmarks:
35
+ landmarks=[]
36
+ for landmark in results.multi_hand_landmarks[0].landmark:
37
+ landmarks.extend([landmark.x, landmark.y])
38
+ return landmarks
39
+ return None
40
+
41
+ def process_image(self, img_path):
42
+ """Process a single image and return cropped image and landmarks."""
43
+ img=cv2.imread(img_path)
44
+ if img is None:
45
+ return None, None
46
+
47
+ imgRGB=cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
48
+ results=self.hands.process(imgRGB)
49
+
50
+ # get landmarks
51
+ landmarks=self.extract_landmarks(results)
52
+ if landmarks is None:
53
+ return None, None
54
+
55
+ # get bbox & crop
56
+ bbox=self.get_bbox_coordinates(results, img.shape)
57
+ if bbox is None:
58
+ return None, None
59
+
60
+ minX, minY, MaxX, MaxY=bbox
61
+ h, w=img.shape[:2]
62
+ minX=max(0, minX-self.offset)
63
+ minY=max(0, minY-self.offset)
64
+ MaxX=min(w, MaxX+self.offset)
65
+ MaxY=min(h, MaxY+self.offset)
66
+
67
+ imgCrop=img[minY:MaxY, minX:MaxX]
68
+ if imgCrop.size==0:
69
+ return None, None
70
+
71
+ return imgCrop, landmarks
72
+
73
+ def process_dataset(self, input_path, output_img_path, output_landmarks_path):
74
+ """Process entire dataset and save cropped images and landmarks."""
75
+ os.makedirs(output_img_path, exist_ok=True)
76
+ os.makedirs(output_landmarks_path, exist_ok=True)
77
+
78
+ landmarks_dict={}
79
+
80
+ for class_name in tqdm(os.listdir(input_path), desc="Processing classes"):
81
+ input_class_path=os.path.join(input_path, class_name)
82
+ if not os.path.isdir(input_class_path):
83
+ continue
84
+
85
+ output_class_path=os.path.join(output_img_path, class_name)
86
+ os.makedirs(output_class_path, exist_ok=True)
87
+
88
+ # img processing
89
+ processed_count=0
90
+ for img_name in os.listdir(input_class_path):
91
+ if processed_count>=self.max_images_per_class:
92
+ break
93
+
94
+ input_img_path=os.path.join(input_class_path, img_name)
95
+ cropped_img, landmarks=self.process_image(input_img_path)
96
+
97
+ if cropped_img is not None and landmarks is not None:
98
+ # export cropped image
99
+ output_img_path_full=os.path.join(output_class_path, img_name)
100
+ cv2.imwrite(output_img_path_full, cropped_img)
101
+
102
+ # store landmarks
103
+ relative_path=os.path.join(class_name, img_name)
104
+ landmarks_dict[relative_path]=landmarks
105
+
106
+ processed_count+=1
107
+
108
+ # export landmarks
109
+ np_path=os.path.join(output_landmarks_path, 'hand_landmarks.npz')
110
+ np.savez_compressed(np_path, **landmarks_dict)
111
+
112
+ print(f"Processed {len(landmarks_dict)} images")
113
+ print(f"Cropped images saved to: {output_img_path}")
114
+ print(f"Landmarks data saved to: {output_landmarks_path}")
115
+
116
+
117
+ if __name__=="__main__":
118
+ input_path="E:/ML_ASL_try/asl_alphabet_train/asl_alphabet_train/"
119
+ output_img_path="E:/ML_ASL_try/new_cropped_images/"
120
+ output_landmarks_path="E:/ML_ASL_try/new_landmarks_data/"
121
+
122
+ processor=HandProcessor()
123
+ processor.process_dataset(input_path, output_img_path, output_landmarks_path)
main_ASL.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import numpy as np
4
+ from Classifier_ASL import Classifier
5
+ from Hand_Tracking_ASL import HandDetector
6
+
7
+ cap=cv2.VideoCapture(0)
8
+ detector=HandDetector(maxHands=1)
9
+ classifier=Classifier("best_model.h5")
10
+ offset=20
11
+
12
+
13
+ def main():
14
+ while True:
15
+ success, img=cap.read()
16
+ hands, img=detector.findHands(img)
17
+
18
+ # initialization for variables
19
+ imgCrop=None
20
+ pred_label=""
21
+ pred_prob=0.0
22
+
23
+ if hands:
24
+ hand=hands[0]
25
+ x, y, w, h=hand['bbox']
26
+
27
+ imgHeight, imgWidth=img.shape[:2]
28
+ y1=max(0, y-offset)
29
+ y2=min(imgHeight, y+h+offset)
30
+ x1=max(0, x-offset)
31
+ x2=min(imgWidth, x+w+offset)
32
+
33
+ imgCrop=img[y1:y2, x1:x2]
34
+
35
+ if imgCrop.size!=0: # Check if the crop is not empty
36
+ pred_label, pred_prob=classifier.get_prediction(imgCrop, hand)
37
+
38
+ cv2.imshow("ImageCrop", imgCrop)
39
+
40
+ large_img=np.zeros((600, 600, 3), dtype=np.uint8)
41
+
42
+ center_y=large_img.shape[0]//2
43
+ center_x=large_img.shape[1]//2
44
+
45
+ top_y=center_y-imgCrop.shape[0]//2
46
+ top_x=center_x-imgCrop.shape[1]//2
47
+
48
+ large_img[top_y:top_y+imgCrop.shape[0], top_x:top_x+imgCrop.shape[1]]=imgCrop
49
+
50
+ cv2.putText(large_img, f"Label: {pred_label}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
51
+ cv2.putText(large_img, f"Prob: {pred_prob:.2%}", (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
52
+ cv2.imshow("Larger Image", large_img)
53
+ print(f'{pred_label}: {pred_prob:.2%}')
54
+
55
+ cv2.putText(img, f"{pred_label}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
56
+ cv2.putText(img, f"{pred_prob:.2%}", (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
57
+
58
+ if cv2.waitKey(1)&0xFF==ord('q'):
59
+ break
60
+
61
+ cap.release()
62
+ cv2.destroyAllWindows()
63
+
64
+
65
+ if __name__=='__main__':
66
+ main()