You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
84 lines
1.9 KiB
84 lines
1.9 KiB
2 months ago
|
from deepface import DeepFace
|
||
|
import glob
|
||
|
import os
|
||
|
import json
|
||
|
import numpy as np
|
||
|
|
||
|
folderPath = "images"
|
||
|
output_file = "embeddings.json"
|
||
|
|
||
|
embeddings = []
|
||
|
|
||
|
backends = [
|
||
|
'opencv',
|
||
|
'ssd',
|
||
|
'dlib',
|
||
|
'mtcnn',
|
||
|
'fastmtcnn',
|
||
|
'retinaface',
|
||
|
'mediapipe',
|
||
|
'yolov8',
|
||
|
'yunet',
|
||
|
'centerface',
|
||
|
]
|
||
|
|
||
|
def main():
|
||
|
image_paths = setup()
|
||
|
run(image_paths)
|
||
|
saveToJson()
|
||
|
|
||
|
def processImage(image, idx):
|
||
|
try:
|
||
|
|
||
|
anaylse_obj = DeepFace.analyze(
|
||
|
img_path=image,
|
||
|
actions=['emotion'],
|
||
|
enforce_detection=False,
|
||
|
detector_backend=backends[0]
|
||
|
)
|
||
|
|
||
|
emotions = anaylse_obj[0]['emotion']
|
||
|
|
||
|
raw_emotions = [value for value in emotions.values()]
|
||
|
|
||
|
normalised_emotions = l2_normalize(np.array(raw_emotions))
|
||
|
|
||
|
normalised_emotions = normalised_emotions.tolist()
|
||
|
|
||
|
entry = {
|
||
|
"index": idx,
|
||
|
"filename": os.path.basename(image), # Extract the filename from the path
|
||
|
"vector": normalised_emotions
|
||
|
}
|
||
|
|
||
|
# Add the entry to the JSON data list
|
||
|
embeddings.append(entry)
|
||
|
except:
|
||
|
print("Could not locate face in image. Skipping.")
|
||
|
|
||
|
def run(image_paths):
|
||
|
for idx, image in enumerate(image_paths):
|
||
|
processImage(image, idx)
|
||
|
|
||
|
def setup():
|
||
|
# List of all images in the specified folder
|
||
|
image_files = glob.glob(os.path.join(folderPath, '*'))
|
||
|
|
||
|
# Optional: Filter by specific image extensions (e.g., .jpg, .png)
|
||
|
image_paths = [img for img in image_files if img.endswith(('.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.gif'))]
|
||
|
|
||
|
return image_paths
|
||
|
|
||
|
def l2_normalize(vector):
|
||
|
norm = np.linalg.norm(vector)
|
||
|
if norm == 0:
|
||
|
return vector
|
||
|
return vector / norm
|
||
|
|
||
|
def saveToJson():
|
||
|
with open(output_file, 'w') as f:
|
||
|
json.dump(embeddings, f, indent=4)
|
||
|
print("Successfully created JSON file.")
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
main()
|