-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhistogram_of_oriented_gradients.py
76 lines (55 loc) · 1.81 KB
/
histogram_of_oriented_gradients.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
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.svm import LinearSVC
from skimage.feature import hog
import numpy as np
import cv2
class HistogramOfOrientedGradients:
def __init__(
self,
classifier: [LinearSVC, RandomForestClassifier]
) -> None:
self.classifier = classifier()
def train(
self,
images: np.ndarray,
labels: np.ndarray
) -> None:
feature_descriptors = []
for image in images:
descriptor = hog(
image,
orientations = 9,
pixels_per_cell = (8, 8),
cells_per_block = (2, 2),
visualize = False
)
feature_descriptors.append(descriptor)
X = np.array(feature_descriptors)
y = labels.ravel()
self.classifier.fit(X, y)
def test(
self,
images: np.ndarray,
labels: np.ndarray
) -> None:
num_instances = images.shape[0]
feature_descriptors = []
for image in images:
descriptor = hog(
image,
orientations = 9,
pixels_per_cell = (8, 8),
cells_per_block = (2, 2),
visualize = False
)
feature_descriptors.append(descriptor)
X = np.array(feature_descriptors)
y_true = labels.ravel()
y_pred = self.classifier.predict(X)
correct = (y_true == y_pred).sum()
accuracy = accuracy_score(y_true, y_pred) * 100
print(f" Total instances: {num_instances}")
print(f"Correct classifications: {correct}")
print(f" Accuracy score: {round(accuracy, 3)}")
return y_pred