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
| import os import cv2 import numpy as np import pickle from sklearn.model_selection import train_test_split import tensorflow as tf from tensorflow import keras from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout import tf2onnx
data_dir = "./leapGestRecog"
img_height, img_width = 96, 96 batch_size = 16
allowed_folders = ['01_palm', '02_l', '03_fist', '04_fist_moved', '05_thumb', '06_index']
X = [] y = [] label_map = {folder: idx for idx, folder in enumerate(allowed_folders)}
for main_folder in sorted(os.listdir(data_dir)): main_folder_path = os.path.join(data_dir, main_folder) if os.path.isdir(main_folder_path): for folder_name in allowed_folders: folder_path = os.path.join(main_folder_path, folder_name) if os.path.isdir(folder_path): label = label_map[folder_name] for img_name in os.listdir(folder_path): img_path = os.path.join(folder_path, img_name) img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) if img is not None: img = cv2.resize(img, (img_width, img_height)) X.append(img) y.append(label)
X = np.array(X).reshape(-1, img_height, img_width, 1) / 255.0 y = np.array(y)
ts = 0.3 X_train, X_test1, y_train, y_test1 = train_test_split(X, y, test_size=ts, random_state=42) X_test, X_cal, y_test, y_cal = train_test_split(X_test1, y_test1, test_size=ts, random_state=42)
with open('X_test.pkl', 'wb') as file: pickle.dump(X_test, file)
with open('y_test.pkl', 'wb') as file: pickle.dump(y_test, file)
with open('X_train.pkl', 'wb') as file: pickle.dump(X_train, file)
with open('y_train.pkl', 'wb') as file: pickle.dump(y_train, file)
print(tf.__version__)
model = Sequential() model.add(Conv2D(32, (5, 5), activation='relu', input_shape=(96, 96, 1))) model.add(MaxPooling2D((2, 2))) model.add(Dropout(0.2)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D((2, 2))) model.add(Dropout(0.2)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D((2, 2))) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dense(6, activation='softmax'))
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
history = model.fit(X_train, y_train, epochs=5, batch_size=64, verbose=1, validation_data=(X_test, y_test))
model.save('handrecognition_model.h5')
model = tf.keras.models.load_model("handrecognition_model.h5")
tf.saved_model.save(model, "tmp_model")
!python -m tf2onnx.convert --saved-model "tmp_model" --output "handrecognition_model.onnx"
|