-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathimage_feature_extraction.py
More file actions
27 lines (23 loc) · 964 Bytes
/
image_feature_extraction.py
File metadata and controls
27 lines (23 loc) · 964 Bytes
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
# Import the libraries
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.vgg16 import VGG16, preprocess_input
from tensorflow.keras.models import Model
import numpy as np
class FeatureExtractor:
def __init__(self):
# Use VGG-16 as the architecture and ImageNet for the weight
base_model = VGG16(weights='imagenet')
# Customize the model to return features from fully-connected layer
self.model = Model(inputs=base_model.input, outputs=base_model.get_layer('fc1').output)
def extract(self, img):
# Resize the image
img = img.resize((224, 224))
# Convert the image color space
img = img.convert('RGB')
# Reformat the image
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
# Extract Features
feature = self.model.predict(x)[0]
return feature / np.linalg.norm(feature)