-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathModelClassificationHardNet2.py
107 lines (81 loc) · 2.89 KB
/
ModelClassificationHardNet2.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
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 12 17:23:05 2022
@author: Simon Bilik
This class is used for the classification of the evaluated model
"""
import logging
import traceback
import cv2 as cv
import numpy as np
from HardNet import HardNet
from skimage.util import view_as_blocks
from ModelClassificationBase import ModelClassificationBase
class ModelClassificationHardNet2(ModelClassificationBase):
## Constructor
def __init__(
self,
modelDataPath,
experimentPath,
modelSel,
layerSel,
labelInfo,
imageDim,
modelData,
anomaly_algorithm_selection = ["Robust covariance", "One-Class SVM", "Isolation Forest", "Local Outlier Factor"],
visualize = True
):
try:
# Call the parent
ModelClassificationBase.__init__(
self,
modelDataPath,
experimentPath,
modelSel,
layerSel,
labelInfo,
imageDim,
modelData,
'HardNet2',
anomaly_algorithm_selection,
visualize
)
except:
traceback.print_exc()
# Create HardNet model object
self.hardNet = HardNet()
# Get data, metrics and classify the data
try:
if self.modelData:
self.procDataFromDict()
else:
self.procDataFromFile()
self.dataClassify()
except:
logging.error('An error occured during classification using ' + self.featExtName + ' feature extraction method...')
traceback.print_exc()
pass
## Compute the classification metrics
def computeMetrics(self, processedData, eps = 1e-6):
# Get the data
diffData = np.subtract(processedData.get('Org'), processedData.get('Dec'))
labels = processedData.get('Lab')
# Initialize the conversion and metric lists
metrics = []
# Get HardNet features for each image
for img in diffData:
# Convert image to gray
if(img.shape[2] == 3):
img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
else:
img = np.squeeze(img)
# Split the image into 32x32 images
batch = view_as_blocks(img, (32, 32))
batch = batch.reshape(batch.shape[0]*batch.shape[1], 32, 32, 1)
# Get HardNet features and its norm
temp = self.hardNet.forward(batch)
norms = np.linalg.norm(temp, None, axis=0)
metrics.append(norms)
# Convert the metrics to np array and normalize them
metrics = self.normalize2DData(np.array(metrics))
return metrics, labels