-
Notifications
You must be signed in to change notification settings - Fork 3
/
adaboost.py
117 lines (91 loc) · 4.14 KB
/
adaboost.py
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import cv2
import os
import numpy as np
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.datasets import load_iris
from sklearn.ensemble import AdaBoostClassifier
import joblib
import cv2
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.model_selection import GridSearchCV
# Define the directory where the hand gesture images are stored
# dataset_dir = "dataset\dataset\Woman"
dataset_dir = "dataset_sample\Women"
labels = []
features=[]
# Define the HOG parameters
win_size = (64, 64)
block_size = (16, 16)
block_stride = (8, 8)
cell_size = (8, 8)
nbins = 9
lower_skin = np.array([0, 135, 85])
upper_skin = np.array([255, 180, 135])
for sub_dir in os.listdir(dataset_dir):
sub_dir_path = os.path.join(dataset_dir, sub_dir)
if not os.path.isdir(sub_dir_path):
continue
# Iterate through each image file in the subdirectory
for file_name in os.listdir(sub_dir_path):
if not file_name.endswith(".JPG"):
continue
image_path = os.path.join(sub_dir_path, file_name)
image = cv2.imread(image_path)
image= cv2.resize(image,(128,128))
ycrcb = cv2.cvtColor(image, cv2.COLOR_BGR2YCrCb)
mask = cv2.inRange(ycrcb, lower_skin, upper_skin)
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contour = max(contours, key = len)
min_x, min_y, w, h = cv2.boundingRect(contour)
new_img = np.zeros((h, w), dtype=np.uint8)
contour = contour - [min_x, min_y]
cv2.drawContours(new_img, [contour], 0, 255, -1)
new_img= cv2.resize(new_img,(128,128))
# Initialize HOG descriptor
hog = cv2.HOGDescriptor(win_size, block_size, block_stride, cell_size, nbins)
# Compute HOG features
hog_features = hog.compute(new_img)
features.append(hog_features)
print(sub_dir)
labels.append(sub_dir)
features = np.array(features)
labels = np.array(labels)
print(labels.shape)
# Split the dataset into training and testing sets
train_features, test_features, train_labels, test_labels = train_test_split(
features, labels, test_size=0.25, random_state=42)
print('Shape of train_images:', train_features.shape)
print('Shape of train_labels:', train_labels.shape)
print('Shape of test_images:', test_features.shape)
print('Shape of test_labels:', test_labels.shape)
# Train a Support Vector Machine (SVM) classifier
svm_classifier = svm.SVC(kernel="linear")
# Initialize weights of training samples
sample_weights = np.ones(len(train_features)) / len(train_features)
# Train Adaboost classifier on training data using SVM as base classifier
# n_estimators = 50
# learning_rate = 1
# Define range of hyperparameters to search over
param_grid = {'n_estimators': [10,50, 100, 150,200,300,350,500,1000], 'learning_rate': [0.0001,0.1, 0.5, 1.0]}
adaboost_clf = AdaBoostClassifier(estimator=svm_classifier,algorithm='SAMME')
grid_search = GridSearchCV(adaboost_clf, param_grid, scoring='accuracy')
grid_search.fit(train_features, train_labels, sample_weight=sample_weights)
best_adaboost_clf = grid_search.best_estimator_
y_val_pred = best_adaboost_clf.predict(test_features)
val_accuracy = accuracy_score(test_labels, y_val_pred)
# val_precision = precision_score(test_labels, y_val_pred)
# val_recall = recall_score(test_labels, y_val_pred)
# val_f1 = f1_score(test_labels, y_val_pred)
# adaboost_clf.fit(train_features, train_labels)
# Save the trained classifier to a file
# joblib.dump(svm_classifier, 'svm_classifier.joblib')
# Predict the labels of the test set using the trained SVM classifier
# predicted_labels = adaboost_clf.predict(test_features)
# Compute the accuracy of the SVM classifier
# accuracy = accuracy_score(test_labels, predicted_labels)
print("Accuracy: {:.4f}%".format(val_accuracy * 100))
# print("Accuracy: {:.4f}%".format(val_precision * 100))
# print("Accuracy: {:.4f}%".format(val_recall * 100))
# print("Accuracy: {:.4f}%".format(val_f1 * 100))