利用Python訓練手勢模型程式碼

GOZO發表於2024-05-23

import cv2 as cv
import os
import numpy as np
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import MultinomialNB
from sklearn.neural_network import MLPClassifier
from sklearn.ensemble import VotingClassifier
from joblib import dump

# 影像預處理函式
def resize_image(img):
# 調整影像大小為200x200畫素
resized_img = cv.resize(img, (200, 200))
# 將影像展平為一維陣列
flattened_img = resized_img.reshape(200 * 200)
return flattened_img


def apply_pca(data):

n_dim = 40
pca = PCA(n_components=n_dim)

X_pca = pca.fit_transform(data)
return X_pca


data = []
labels = []

for path, dirs, files in os.walk('./img02'):

label = path.split(os.sep)[-1]
if len(label) > 0:

for file in files:
file_path = os.path.join(path, file)

img = cv.imread(file_path, 0)
if img is not None:

data.append(resize_image(img))

labels.append(label)


data_x = np.array(data)
target_y = np.array(labels)


x_update = apply_pca(data_x)


x_train, x_test, y_train, y_test = train_test_split(data_x, target_y, random_state=42, test_size=0.25)


models = {
"SVM": SVC(C=2.0, max_iter=100),
"Decision Tree": DecisionTreeClassifier(),
"KNN": KNeighborsClassifier(),
"Naive Bayes": MultinomialNB(),
"Neural Network": MLPClassifier(max_iter=200, hidden_layer_sizes=(40, 30, 20, 10)),
"Voting": VotingClassifier(estimators=[
("lw1", SVC(probability=True)),
("lw2", DecisionTreeClassifier()),
("lw3", KNeighborsClassifier()),
("lw4", MultinomialNB())], voting="soft", weights=[1, 1, 1, 1])
}


for name, model in models.items():

model.fit(x_train, y_train)

accuracy = model.score(x_test, y_test)

print(f"{name} 精度: {accuracy}")


for name, model in models.items():

dump(model, f"{name.lower()}.dat")

相關文章