This commit is contained in:
Onur Atakan ULUSOY 2022-05-24 13:59:16 +00:00 committed by GitHub
parent 4cc2fd8782
commit 84a1ac64a5

View File

@ -1,353 +1,223 @@
import warnings import warnings
warnings.filterwarnings("ignore")
import os import os
#os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import tensorflow as tf
import cv2
from deepface import DeepFace
print("-----------------------------------------")
warnings.filterwarnings("ignore")
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import json tf_major_version = int(tf.__version__.split(".")[0])
import time
import unittest
#----------------------------------------- if tf_major_version == 2:
import logging
tf.get_logger().setLevel(logging.ERROR)
import tensorflow as tf print("Running unit tests for TF ", tf.__version__)
class deepface_unit_tests(unittest.TestCase): print("-----------------------------------------")
def test_deepface(self): expected_coverage = 97
tf_version = int(tf.__version__.split(".")[0]) num_cases = 0; succeed_cases = 0
if tf_version == 2: def evaluate(condition):
import logging
tf.get_logger().setLevel(logging.ERROR)
print("Running unit tests for TF ", tf.__version__) global num_cases, succeed_cases
from deepface import DeepFace if condition is True:
from deepface.commons import functions succeed_cases += 1
from deepface.basemodels import VGGFace, OpenFace, Facenet, FbDeepFace
from deepface.extendedmodels import Age, Gender, Race, Emotion num_cases += 1
print("-----------------------------------------") # ------------------------------------------------
#-----------------------------------------
print("DeepFace.detectFace test") detectors = ['opencv', 'mtcnn', 'retinaface']
#detectors = ['opencv', 'ssd', 'dlib', 'mtcnn', 'retinaface'] models = ['VGG-Face', 'Facenet', 'Facenet512', 'ArcFace', 'SFace']
detectors = ['opencv', 'ssd', 'mtcnn', 'retinaface'] metrics = ['cosine', 'euclidean', 'euclidean_l2']
for detector in detectors: dataset = [
img = DeepFace.detectFace("dataset/img11.jpg", detector_backend = detector) ['dataset/img1.jpg', 'dataset/img2.jpg', True],
print(detector," test is done") ['dataset/img5.jpg', 'dataset/img6.jpg', True],
['dataset/img6.jpg', 'dataset/img7.jpg', True],
['dataset/img8.jpg', 'dataset/img9.jpg', True],
['dataset/img1.jpg', 'dataset/img11.jpg', True],
['dataset/img2.jpg', 'dataset/img11.jpg', True],
#import matplotlib.pyplot as plt ['dataset/img1.jpg', 'dataset/img3.jpg', False],
#plt.imshow(img) ['dataset/img2.jpg', 'dataset/img3.jpg', False],
#plt.show() ['dataset/img6.jpg', 'dataset/img8.jpg', False],
['dataset/img6.jpg', 'dataset/img9.jpg', False],
]
#----------------------------------------- print("-----------------------------------------")
print("-----------------------------------------")
img_path = "dataset/img1.jpg" def test_cases():
embedding = DeepFace.represent(img_path)
print("Function returned ", len(embedding), "dimensional vector")
model_name = "VGG-Face" print("DeepFace.detectFace test")
model = DeepFace.build_model(model_name)
print(model_name," is built")
embedding = DeepFace.represent(img_path, model = model)
print("Represent function returned ", len(embedding), "dimensional vector")
#----------------------------------------- for detector in detectors:
img = DeepFace.detectFace("dataset/img11.jpg", detector_backend = detector)
evaluate(img.shape[0] > 0 and img.shape[1] > 0)
print(detector," test is done")
dataset = [ print("-----------------------------------------")
['dataset/img1.jpg', 'dataset/img2.jpg', True],
['dataset/img1.jpg', 'dataset/img6.jpg', True]
]
print("-----------------------------------------") img_path = "dataset/img1.jpg"
embedding = DeepFace.represent(img_path)
print("Function returned ", len(embedding), "dimensional vector")
evaluate(len(embedding) > 0)
print("Face detectors test") print("-----------------------------------------")
print("retinaface detector") print("Face detectors test")
res = DeepFace.verify(dataset, detector_backend = 'retinaface')
print(res)
print("ssd detector") for detector in detectors:
res = DeepFace.verify(dataset, detector_backend = 'ssd') print(detector + " detector")
print(res) res = DeepFace.verify(dataset[0][0], dataset[0][1], detector_backend = detector)
print(res)
assert res["verified"] == dataset[0][2]
print("opencv detector") print("-----------------------------------------")
res = DeepFace.verify(dataset, detector_backend = 'opencv')
print(res)
if False: print("Find function test")
print("dlib detector")
res = DeepFace.verify(dataset, detector_backend = 'dlib')
print(res)
print("mtcnn detector") df = DeepFace.find(img_path = "dataset/img1.jpg", db_path = "dataset")
res = DeepFace.verify(dataset, detector_backend = 'mtcnn') print(df.head())
print(res) evaluate(df.shape[0] > 0)
print("-----------------------------------------") print("-----------------------------------------")
print("Single find function test") print("Facial analysis test. Passing nothing as an action")
df = DeepFace.find(img_path = "dataset/img1.jpg", db_path = "dataset" img = "dataset/img4.jpg"
#, model_name = 'Dlib' demography = DeepFace.analyze(img)
) print(demography)
print(df.head())
print("-----------------------------------------") evaluate(demography["age"] > 20 and demography["age"] < 40)
evaluate(demography["gender"] == "Woman")
print("Pre-built model for single find function test") print("-----------------------------------------")
#model_name = "VGG-Face" print("Facial analysis test. Passing all to the action")
#model = DeepFace.build_model(model_name) demography = DeepFace.analyze(img, ['age', 'gender', 'race', 'emotion'])
#print(model_name," is built")
df = DeepFace.find(img_path = "dataset/img1.jpg", db_path = "dataset" print("Demography:")
, model_name = model_name, model = model print(demography)
)
print(df.head())
print("-----------------------------------------") #check response is a valid json
print("Age: ", demography["age"])
print("Gender: ", demography["gender"])
print("Race: ", demography["dominant_race"])
print("Emotion: ", demography["dominant_emotion"])
print("Bulk find function tests") evaluate(demography.get("age") is not None)
evaluate(demography.get("gender") is not None)
evaluate(demography.get("dominant_race") is not None)
evaluate(demography.get("dominant_emotion") is not None)
dfs = DeepFace.find(img_path = ["dataset/img1.jpg", "dataset/img2.jpg"], db_path = "dataset" print("-----------------------------------------")
#, model_name = 'Dlib'
)
print(dfs[0].head())
print(dfs[1].head())
print("-----------------------------------------") print("Facial analysis test 2. Remove some actions and check they are not computed")
demography = DeepFace.analyze(img, ['age', 'gender'])
print("Bulk verification tests") print("Age: ", demography.get("age"))
print("Gender: ", demography.get("gender"))
print("Race: ", demography.get("dominant_race"))
print("Emotion: ", demography.get("dominant_emotion"))
resp_obj = DeepFace.verify(dataset) evaluate(demography.get("age") is not None)
print(resp_obj) evaluate(demography.get("gender") is not None)
print(resp_obj["pair_1"]["verified"] == True) evaluate(demography.get("dominant_race") is None)
print(resp_obj["pair_2"]["verified"] == True) evaluate(demography.get("dominant_emotion") is None)
print("-----------------------------------------") print("-----------------------------------------")
print("Bulk facial analysis tests") print("Facial recognition tests")
dataset = [ for model in models:
'dataset/img1.jpg', for metric in metrics:
'dataset/img2.jpg', for instance in dataset:
'dataset/img5.jpg', img1 = instance[0]
'dataset/img6.jpg' img2 = instance[1]
] result = instance[2]
resp_obj = DeepFace.analyze(dataset) resp_obj = DeepFace.verify(img1, img2
print(resp_obj["instance_1"]["age"]," years old ", resp_obj["instance_1"]["dominant_emotion"], " ",resp_obj["instance_1"]["gender"]) , model_name = model
print(resp_obj["instance_2"]["age"]," years old ", resp_obj["instance_2"]["dominant_emotion"], " ",resp_obj["instance_2"]["gender"]) , distance_metric = metric)
print(resp_obj["instance_3"]["age"]," years old ", resp_obj["instance_3"]["dominant_emotion"], " ",resp_obj["instance_3"]["gender"])
print(resp_obj["instance_4"]["age"]," years old ", resp_obj["instance_4"]["dominant_emotion"], " ",resp_obj["instance_4"]["gender"])
print("-----------------------------------------") prediction = resp_obj["verified"]
distance = round(resp_obj["distance"], 2)
threshold = resp_obj["threshold"]
print("Facial analysis test. Passing nothing as an action") passed = prediction == result
img = "dataset/img4.jpg" evaluate(passed)
demography = DeepFace.analyze(img)
print(demography)
print("-----------------------------------------") if passed:
test_result_label = "passed"
else:
test_result_label = "failed"
print("Facial analysis test. Passing all to the action") if prediction == True:
demography = DeepFace.analyze(img, ['age', 'gender', 'race', 'emotion']) classified_label = "verified"
else:
classified_label = "unverified"
print("Demography:") print(img1.split("/")[-1], "-", img2.split("/")[-1], classified_label, "as same person based on", model,"and",metric,". Distance:",distance,", Threshold:", threshold,"(",test_result_label,")")
print(demography)
#check response is a valid json print("--------------------------")
print("Age: ", demography["age"])
print("Gender: ", demography["gender"])
print("Race: ", demography["dominant_race"])
print("Emotion: ", demography["dominant_emotion"])
print("-----------------------------------------") # -----------------------------------------
print("Passing numpy array to analyze function")
print("Facial analysis test 2. Remove some actions and check they are not computed") img = cv2.imread("dataset/img1.jpg")
demography = DeepFace.analyze(img, ['age', 'gender']) resp_obj = DeepFace.analyze(img)
print(resp_obj)
print("Age: ", demography.get("age")) evaluate(resp_obj["age"] > 20 and resp_obj["age"] < 40)
print("Gender: ", demography.get("gender")) evaluate(resp_obj["gender"] == "Woman")
print("Race: ", demography.get("dominant_race"))
print("Emotion: ", demography.get("dominant_emotion"))
print("--------------------------")
print("-----------------------------------------") print("Passing numpy array to verify function")
print("Face recognition tests") img1 = cv2.imread("dataset/img1.jpg")
img2 = cv2.imread("dataset/img2.jpg")
dataset = [ res = DeepFace.verify(img1, img2)
['dataset/img1.jpg', 'dataset/img2.jpg', True], print(res)
['dataset/img5.jpg', 'dataset/img6.jpg', True],
['dataset/img6.jpg', 'dataset/img7.jpg', True],
['dataset/img8.jpg', 'dataset/img9.jpg', True],
['dataset/img1.jpg', 'dataset/img11.jpg', True],
['dataset/img2.jpg', 'dataset/img11.jpg', True],
['dataset/img1.jpg', 'dataset/img3.jpg', False], evaluate(res["verified"] == True)
['dataset/img2.jpg', 'dataset/img3.jpg', False],
['dataset/img6.jpg', 'dataset/img8.jpg', False],
['dataset/img6.jpg', 'dataset/img9.jpg', False],
]
#models = ['VGG-Face', 'Facenet', 'OpenFace', 'DeepFace', 'DeepID', 'Dlib', 'ArcFace'] print("--------------------------")
models = ['VGG-Face', 'Facenet', 'Facenet512', 'ArcFace', 'SFace'] #those are robust models
metrics = ['cosine', 'euclidean', 'euclidean_l2']
passed_tests = 0; test_cases = 0 print("Passing numpy array to find function")
for model in models: img1 = cv2.imread("dataset/img1.jpg")
#prebuilt_model = DeepFace.build_model(model)
#print(model," is built")
for metric in metrics:
for instance in dataset:
img1 = instance[0]
img2 = instance[1]
result = instance[2]
resp_obj = DeepFace.verify(img1, img2 df = DeepFace.find(img1, db_path = "dataset")
, model_name = model
#, model = prebuilt_model
, distance_metric = metric)
prediction = resp_obj["verified"] print(df.head())
distance = round(resp_obj["distance"], 2)
threshold = resp_obj["threshold"]
test_result_label = "failed" evaluate(df.shape[0] > 0)
if prediction == result:
passed_tests = passed_tests + 1
test_result_label = "passed"
if prediction == True: print("--------------------------")
classified_label = "verified"
else:
classified_label = "unverified"
test_cases = test_cases + 1 test_cases()
print(img1.split("/")[-1], "-", img2.split("/")[-1], classified_label, "as same person based on", model,"and",metric,". Distance:",distance,", Threshold:", threshold,"(",test_result_label,")") print("num of test cases run: " + str(num_cases))
print("succeeded test cases: " + str(succeed_cases))
print("--------------------------") test_score = (100 * succeed_cases) / num_cases
#----------------------------------------- print("test coverage: " + str(test_score))
print("Passed unit tests: ",passed_tests," / ",test_cases) if test_score > expected_coverage:
print("well done! min required test coverage is satisfied")
else:
print("min required test coverage is NOT satisfied")
min_score = 70 assert test_score > expected_coverage
accuracy = 100 * passed_tests / test_cases
accuracy = round(accuracy, 2)
if accuracy >= min_score:
print("Unit tests are completed successfully. Score: ",accuracy,"%")
else:
raise ValueError("Unit test score does not satisfy the minimum required accuracy. Minimum expected score is ", min_score,"% but this got ",accuracy,"%")
#-----------------------------------
#-----------------------------------
print("Analyze function with passing pre-trained model")
emotion_model = DeepFace.build_model("Emotion")
age_model = DeepFace.build_model("Age")
gender_model = DeepFace.build_model("Gender")
race_model = DeepFace.build_model("Race")
facial_attribute_models = {}
facial_attribute_models["emotion"] = emotion_model
facial_attribute_models["age"] = age_model
facial_attribute_models["gender"] = gender_model
facial_attribute_models["race"] = race_model
resp_obj = DeepFace.analyze("dataset/img1.jpg", models=facial_attribute_models)
print(resp_obj)
#-----------------------------------
print("--------------------------")
if False:
print("Ensemble for find function")
df = DeepFace.find(img_path = "dataset/img1.jpg", db_path = "dataset", model_name = "Ensemble")
print(df.head())
#-----------------------------------
print("--------------------------")
if False:
print("Ensemble for verify function")
resp_obj = DeepFace.verify(dataset, model_name = "Ensemble")
for i in range(0, len(dataset)):
item = resp_obj['pair_%s' % (i+1)]
verified = item["verified"]
score = item["score"]
print(verified)
#-----------------------------------
print("--------------------------")
if False:
print("Pre-trained ensemble method - find")
from deepface import DeepFace
from deepface.basemodels import Boosting
model = Boosting.loadModel()
df = DeepFace.find("dataset/img1.jpg", db_path = "dataset", model_name = 'Ensemble', model = model, enforce_detection=False)
print(df)
#-----------------------------------
print("--------------------------")
if False:
print("Pre-trained ensemble method - verify")
res = DeepFace.verify(dataset, model_name = "Ensemble", model = model)
print(res)
#-----------------------------------
print("--------------------------")
import cv2
print("Passing numpy array to analyze function")
img = cv2.imread("dataset/img1.jpg")
resp_obj = DeepFace.analyze(img)
print(resp_obj)
print("--------------------------")
print("Passing numpy array to verify function")
img1 = cv2.imread("dataset/img1.jpg")
img2 = cv2.imread("dataset/img2.jpg")
res = DeepFace.verify(img1, img2)
print(res)
print("--------------------------")
print("Passing numpy array to find function")
img1 = cv2.imread("dataset/img1.jpg")
df = DeepFace.find(img1, db_path = "dataset")
print(df.head())
print("--------------------------")
self.assertEqual(accuracy >= min_score, True, "A problem on the deepface installation.")
unittest.main(exit=False)