-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
36 lines (32 loc) · 1.5 KB
/
Copy pathmodel.py
File metadata and controls
36 lines (32 loc) · 1.5 KB
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
import tensorflow as tf
import numpy as np
from numpy import linalg
from keras.applications.vgg16 import VGG16
from keras.applications.vgg16 import preprocess_input
class VGGNet:
def __init__(self):
self.input_shape = (224, 224, 3)
self.weight = 'imagenet'
self.pooling = 'max'
self.model = VGG16(weights=self.weight,
input_shape=(self.input_shape[0], self.input_shape[1], self.input_shape[2]),
pooling=self.pooling,
include_top=False)
self.model.predict(np.zeros((1, 224, 224, 3)))
def extract_feature(self, img_path: any, verbose='auto'):
if isinstance(img_path, str) or isinstance(img_path, np.str_):
img = tf.keras.utils.load_img(img_path, target_size=(self.input_shape[0], self.input_shape[1]))
img = tf.keras.utils.img_to_array(img)
img = np.expand_dims(img, axis=0)
img = preprocess_input(img)
feature = self.model.predict(img, verbose=verbose)
feature_normalized = feature[0] / linalg.norm(feature[0])
elif isinstance(img_path, np.ndarray):
img = img_path
img = np.expand_dims(img, axis=0)
img = preprocess_input(img)
feature = self.model.predict(img, verbose=verbose)
feature_normalized = feature[0] / linalg.norm(feature[0])
else:
raise TypeError('img_path must be str or np.ndarray')
return feature_normalized