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 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
| import cv2 as cv import numpy as np import os import random import math import matplotlib.pyplot as plt from sklearn import svm from sklearn.preprocessing import StandardScaler from sklearn.neural_network import MLPClassifier %matplotlib class HoG(object) : def __init__(self, img, cell_w, bin_count) : rows, cols = img.shape img = np.power(img / 255.0, 2.2) * 255 self.img = img self.cell_w = cell_w self.bin_count = bin_count self.angle_unit = 180.0 / bin_count self.cell_x = int(rows / cell_w) self.cell_y = int(cols / cell_w)
def Pixel_gradient(self) : gradient_values_x = cv.Sobel(self.img, cv.CV_64F, 1, 0, ksize = 5) gradient_values_y = cv.Sobel(self.img, cv.CV_64F, 0, 1, ksize = 5) gradient_magnitude = np.sqrt(np.power(gradient_values_x, 2) + np.power(gradient_values_y, 2))
gradient_angle = np.arctan2( gradient_values_x, gradient_values_y ) gradient_angle[ gradient_angle > 0 ] *= 180 / 3.14 gradient_angle[ gradient_angle < 0 ] = ( gradient_angle[ gradient_angle < 0 ] + 3.14 ) * 180 / 3.14
return gradient_magnitude, gradient_angle def Cell_gradient(self, gradient) : cell = np.zeros((self.cell_x, self.cell_y, self.cell_w, self.cell_w)) gradient_x = np.split(gradient, self.cell_x, axis = 0) for i in range(self.cell_x) : gradient_y = np.split(gradient_x[i], self.cell_y, axis = 1) for j in range(self.cell_y) : cell[i][j] = gradient_y[j] return cell
def Get_bins(self, cell_gradient, cell_angle) : bins = np.zeros((cell_gradient.shape[0], cell_gradient.shape[1], self.bin_count)) for i in range(bins.shape[0]) : for j in range(bins.shape[1]) : tmp_unit = np.zeros(self.bin_count) cell_gradient_list = np.int8(cell_gradient[i][j].flatten()) cell_angle_list = cell_angle[i][j].flatten() cell_angle_list = np.int8( cell_angle_list / self.angle_unit ) cell_angle_list[ cell_angle_list >=9 ] = 0
for m in range(len(cell_angle_list)) : tmp_unit[cell_angle_list[m]] += int(cell_gradient_list[m]) bins[i][j] = tmp_unit return bins def Block_Vector(self) : gradient_magnitude, gradient_angle = self.Pixel_gradient() cell_gradient_values = self.Cell_gradient(gradient_magnitude) cell_angle = self.Cell_gradient(gradient_angle) bins = self.Get_bins(cell_gradient_values, cell_angle) block_vector = [] for i in range(self.cell_x - 1) : for j in range(self.cell_y - 1) : feature = [] feature.extend(bins[i][j]) feature.extend(bins[i + 1][j]) feature.extend(bins[i][j + 1]) feature.extend(bins[i + 1][j + 1]) mag = lambda vector : math.sqrt(sum(i ** 2 for i in vector)) magnitude = mag(feature) if magnitude != 0 : normalize = lambda vector, magnitude: [element / magnitude for element in vector] feature = normalize(feature, magnitude) block_vector.extend(feature) return np.array(block_vector) class PCA() : def __init__(self, n_components) : self.n_components = n_components def fit(self, X) : def deMean(X) : return X - np.mean(X, axis = 0) def calcCov(X) : return np.cov(X, rowvar = False) def deEigenvalue(cov) : return np.linalg.eig(cov) n, self.d = X.shape assert self.n_components <= self.d assert self.n_components <= n X = deMean(X) cov = calcCov(X) eigenvalue, featurevector = deEigenvalue(cov) index = np.argsort(eigenvalue) n_index = index[-self.n_components : ] self.w = featurevector[ : , n_index] return self def transform(self, X) : n, d = X.shape assert d == self.d return np.dot(X, self.w)
class DataSet(object) : def __init__(self, root, division) : self.root = root self.division = division def data_segmentation(self, car, dog, face, snake) : train_car, test_car = car[ : int(car.shape[0] * self.division)], car[int(car.shape[0] * self.division) : ] train_car_target, test_car_target = np.full(len(train_car) , 1, dtype = np.int64), np.full(len(test_car) , 1, dtype = np.int64) train_dog, test_dog = dog[ : int(dog.shape[0] * self.division)], dog[int(dog.shape[0] * self.division) : ] train_dog_target, test_dog_target = np.full(len(train_dog) , 2, dtype = np.int64), np.full(len(test_dog) , 2, dtype = np.int64) train_face, test_face = face[ : int(face.shape[0] * self.division)], face[int(face.shape[0] * self.division) : ] train_face_target, test_face_target = np.full(len(train_face) , 3, dtype = np.int64), np.full(len(test_face) , 3, dtype = np.int64) train_snake, test_snake = snake[ : int(snake.shape[0] * self.division)], snake[int(snake.shape[0] * self.division) : ] train_snake_target, test_snake_target = np.full(len(train_snake) , 4, dtype = np.int64), np.full(len(test_snake) , 4, dtype = np.int64)
train_data = np.concatenate([train_car, train_dog, train_face, train_snake]) test_data = np.concatenate([test_car, test_dog, test_face, test_snake]) train_target = np.concatenate([train_car_target, train_dog_target, train_face_target, train_snake_target]) test_target = np.concatenate([test_car_target, test_dog_target, test_face_target, test_snake_target]) index = [i for i in range(len(train_data))] random.shuffle(index) train_data = train_data[index] train_target = train_target[index] return train_data, train_target, test_data, test_target def datasets(self) : image_car = list(sorted(os.listdir(os.path.join(self.root, 'car')))) image_dog = list(sorted(os.listdir(os.path.join(self.root, 'dog')))) image_face = list(sorted(os.listdir(os.path.join(self.root, 'face')))) image_snake = list(sorted(os.listdir(os.path.join(self.root, 'snake')))) car = np.zeros((4000, 256, 256), dtype = np.uint8) dog = np.zeros((4000, 256, 256), dtype = np.uint8) face = np.zeros((4000, 256, 256), dtype = np.uint8) snake = np.zeros((4000, 256, 256), dtype = np.uint8) for i in range(4000) : img = cv.imread(os.path.join(self.root, 'car', image_car[i]), cv.IMREAD_GRAYSCALE) img = cv.resize(img, (256, 256), cv.INTER_CUBIC) car[i] = img for i in range(4000) : img = cv.imread(os.path.join(self.root, 'dog', image_dog[i]), cv.IMREAD_GRAYSCALE) img = cv.resize(img, (256, 256), cv.INTER_CUBIC) dog[i] = img for i in range(4000) : img = cv.imread(os.path.join(self.root, 'face', image_face[i]), cv.IMREAD_GRAYSCALE) img = cv.resize(img, (256, 256), cv.INTER_CUBIC) face[i] = img for i in range(4000) : img = cv.imread(os.path.join(self.root, 'snake', image_snake[i]), cv.IMREAD_GRAYSCALE) img = cv.resize(img, (256, 256), cv.INTER_CUBIC) snake[i] = img print(car.shape, dog.shape, face.shape, snake.shape) train_data, train_target, test_data, test_target = self.data_segmentation(car, dog, face, snake) return train_data, train_target, test_data, test_target def micro_f1(pred, target) : target1 = target.copy() pred1 = pred.copy() target1 = target1 == 1 pred1 = pred1 == 1 TP1 = np.sum(target1[pred1 == 1] == 1) FN1 = np.sum(target1[pred1 == 0] == 1) FP1 = np.sum(target1[pred1 == 1] == 0) TN1 = np.sum(target1[pred1 == 0] == 0) target2 = target.copy() pred2 = pred.copy() target2 = target2 == 2 pred2 = pred2 == 2 TP2 = np.sum(target2[pred2 == 1] == 1) FN2 = np.sum(target2[pred2 == 0] == 1) FP2 = np.sum(target2[pred2 == 1] == 0) TN2 = np.sum(target2[pred2 == 0] == 0) target3 = target.copy() pred3 = pred.copy() target3 = target3 == 3 pred3 = pred3 == 3 TP3 = np.sum(target3[pred3 == 1] == 1) FN3 = np.sum(target3[pred3 == 0] == 1) FP3 = np.sum(target3[pred3 == 1] == 0) TN3 = np.sum(target3[pred3 == 0] == 0) target4 = target.copy() pred4 = pred.copy() target4 = target4 == 4 pred4 = pred4 == 4 TP4 = np.sum(target4[pred4 == 1] == 1) FN4 = np.sum(target4[pred4 == 0] == 1) FP4 = np.sum(target4[pred4 == 1] == 0) TN4 = np.sum(target4[pred4 == 0] == 0) TP = TP1 + TP2 + TP3 + TP4 FN = FN1 + FN2 + FN3 + FN4 FP = FP1 + FP2 + FP3 + FP4 TN = TN1 + TN2 + TN3 + TN4 precision = TP / (TP + FP) recall = TP / (TP + FN) f1 = 2 * precision * recall / (precision + recall) confusion_matrix =np.array([[np.sum(pred[target == 1] == 1), np.sum(pred[target == 1] == 2), np.sum(pred[target == 1] == 3), np.sum(pred[target == 1] == 4)], [np.sum(pred[target == 2] == 1), np.sum(pred[target == 2] == 2), np.sum(pred[target == 2] == 3), np.sum(pred[target == 2] == 4)], [np.sum(pred[target == 3] == 1), np.sum(pred[target == 3] == 2), np.sum(pred[target == 3] == 3), np.sum(pred[target == 3] == 4)], [np.sum(pred[target == 4] == 1), np.sum(pred[target == 4] == 2), np.sum(pred[target == 4] == 3), np.sum(pred[target == 4] == 4)]]) return precision, recall, f1, TP1, TP2, TP3, TP4, confusion_matrix
dataset = DataSet(root = 'data', division = 0.875) train_data, train_target, test_data, test_target = dataset.datasets()
def plot_confusion_matrix(cm, classes, title = 'Confusion matrix', cmap = plt.cm.Blues): plt.imshow(cm, interpolation='nearest', cmap = cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes) plt.yticks(tick_marks, classes) thresh = cm.max() / 2. for i in range(cm.shape[0]) : for j in range(cm.shape[1]) : plt.text(j, i, f'{cm[i][j]}', horizontalalignment="center", color="white" if cm[i][j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') plt.show()
train_feature = [] test_feature = [] for i in range(len(train_data)) : hog = HoG(train_data[i], 32, 9) temp_feature = hog.Block_Vector() train_feature.append(temp_feature) for i in range(len(test_data)) : hog = HoG(test_data[i], 32, 9) temp_feature = hog.Block_Vector() test_feature.append(temp_feature)
train_feature = np.array(train_feature) test_feature = np.array(test_feature)
pca = PCA(n_components = 704) pca.fit(train_feature) train_reduction = pca.transform(train_feature) test_reduction = pca.transform(test_feature) print(train_reduction.shape) print(test_reduction.shape)
clf = svm.SVC() clf.fit(train_reduction, train_target) print(clf.score(test_reduction, test_target)) print(clf.score(train_reduction, train_target)) pred = clf.predict(test_reduction) precision, recall, f1, TP1, TP2, TP3, TP4, confusion_matrix = micro_f1(pred, test_target) print( precision, recall, f1, TP1, TP2, TP3, TP4, confusion_matrix)
plot_confusion_matrix(cm = confusion_matrix, classes = ['car', 'dog', 'face', 'snake'])
|