-
Notifications
You must be signed in to change notification settings - Fork 0
/
extract_embeddings.py
182 lines (143 loc) · 7.11 KB
/
extract_embeddings.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
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
import os
from pickle import loads
from typing import Any, Dict, List, Optional, Tuple
from cv2 import imread
from keras.models import load_model
from numpy import array, ndarray, setdiff1d, unique
rootdir = os.getcwd()
class ExtractEmbeddings:
"""
The ExtractEmbeddings class provides methods for working with facial embeddings,
including loading a model, checking a pretrained file, extracting staff details,
retrieving face pixels, and normalizing pixel values.
Args:
model_path (str): The path to the facial embeddings model.
Attributes:
model_path (str): The path to the facial embeddings model.
dataset_dir (str): The directory containing the dataset.
Methods:
load_model(): Loads the facial embeddings model.
check_pretrained_file(embeddings_model: str) -> Tuple[np.ndarray, List[str]]:
Checks if a pretrained file exists and returns the loaded data and unique names.
get_staff_details() -> Dict[str, str]:
Retrieves staff details from the dataset directory.
get_remaining_names(dictionaries: Dict[str, Any], unique_names: List[str]) -> List[str]:
Returns a list of names present in dictionaries but not in unique_names.
get_all_face_pixels(dictionaries: Dict[str, Any]) -> Tuple[List[str], List[str], List[np.ndarray], List[str], List[str]]:
Retrieves all face pixels, image IDs, paths, arrays, names, and face IDs.
get_remaining_face_pixels(dictionaries: Dict[str, Any], remaining_names: List[str]) -> Optional[Tuple[List[str], List[str], List[np.ndarray], List[str], List[str]]]:
Retrieves face pixels for specified remaining names from dictionaries.
normalize_pixels(imagearrays: List[np.ndarray]) -> np.ndarray:
Normalizes pixel values of the input image arrays.
"""
def __init__(self, model_path: str):
"""
Initializes an instance of the ExtractEmbeddings class.
Args:
model_path (str): The path to the facial embeddings model.
"""
self.model_path = model_path
self.dataset_dir = os.path.join(rootdir, "dataset")
def load_model(self) -> Any:
"""
Loads the facial embeddings model.
Returns:
Any: The loaded facial embeddings model.
"""
return load_model(self.model_path)
def check_pretrained_file(self, embeddings_model: str) -> Tuple[ndarray, List[str]]:
"""
Checks if a pretrained file exists and returns the loaded data and unique names.
Args:
embeddings_model (str): The path to a pretrained embeddings model.
Returns:
Tuple[np.ndarray, List[str]]: A tuple containing the loaded data and unique names.
"""
self.embeddings_model = embeddings_model
with open(embeddings_model, "rb") as file:
data = loads(file.read())
names = array(data["names"])
unique_names = unique(names).tolist()
return data, unique_names
def get_staff_details(self) -> Dict[str, str]:
"""
Retrieves staff details from the dataset directory.
Returns:
Dict[str, str]: A dictionary containing staff names as keys and corresponding IDs as values.
"""
details = os.listdir(self.dataset_dir)
staff_details = {item.split("_")[0]: item.split("_")[1] for item in details}
return staff_details
def get_remaining_names(
self, dictionaries: Dict[str, Any], unique_names: List[str]
) -> List[str]:
"""
Returns a list of names present in dictionaries but not in unique_names.
Args:
dictionaries (Dict[str, Any]): A dictionary object containing multiple dictionaries.
unique_names (List[str]): A list of names considered unique.
Returns:
List[str]: A list of names present in dictionaries but not in unique_names.
"""
return setdiff1d(list(dictionaries.keys()), unique_names).tolist()
def get_all_face_pixels(
self, dictionaries: Dict[str, Any]
) -> Tuple[List[str], List[str], List[ndarray], List[str], List[str]]:
"""
Retrieves all face pixels, image IDs, paths, arrays, names, and face IDs.
Args:
dictionaries (Dict[str, Any]): A dictionary containing categories and their corresponding face IDs.
Returns:
Tuple[List[str], List[str], List[np.ndarray], List[str], List[str]]:
A tuple containing lists of image IDs, paths, arrays, names, and face IDs.
"""
image_ids, image_paths, image_arrays, names, face_ids = [], [], [], [], []
for category, face_id in dictionaries.items():
path = os.path.join(self.dataset_dir, f"{category}_{face_id}")
for img in os.listdir(path):
img_array = imread(os.path.join(path, img))
image_paths.append(os.path.join(path, img))
image_ids.append(img)
image_arrays.append(img_array)
names.append(category)
face_ids.append(face_id)
return image_ids, image_paths, image_arrays, names, face_ids
def get_remaining_face_pixels(
self, dictionaries: Dict[str, Any], remaining_names: List[str]
) -> Optional[Tuple[List[str], List[str], List[ndarray], List[str], List[str]]]:
"""
Retrieves face pixels for specified remaining names from dictionaries.
Args:
dictionaries (Dict[str, Any]): A dictionary mapping category names to face IDs.
remaining_names (List[str]): A list of names representing categories or labels for the images.
Returns:
Optional[Tuple[List[str], List[str], List[np.ndarray], List[str], List[str]]]:
A tuple containing lists of image IDs, paths, arrays, names, and face IDs, or None if remaining_names is empty.
"""
if not remaining_names:
return None
image_ids, image_paths, image_arrays, names, face_ids = [], [], [], [], []
for category in remaining_names:
path = os.path.join(
self.dataset_dir, f"{category}_{dictionaries[category]}"
)
for img in os.listdir(path):
img_array = imread(os.path.join(path, img))
image_paths.append(os.path.join(path, img))
image_ids.append(img)
image_arrays.append(img_array)
names.append(category)
face_ids.append(dictionaries[category])
return image_ids, image_paths, image_arrays, names, face_ids
def normalize_pixels(self, imagearrays: List[ndarray]) -> ndarray:
"""
Normalizes pixel values of the input image arrays.
Args:
imagearrays (List[np.ndarray]): A list containing the pixel values of multiple images.
Returns:
np.ndarray: The normalized pixel values of the input image arrays.
"""
face_pixels = array(imagearrays).astype("float32")
mean, std = face_pixels.mean(), face_pixels.std()
face_pixels = (face_pixels - mean) / std
return face_pixels