def video_verification(photo_path): original_img = cv2.imread(photo_path) original_img_copy = cv2.resize(original_img.copy(), (500, 500)) cv2.imshow('Original', original_img_copy) # уменьшение размера фото, чтобы сеть могла его обработать original_img = cv2.resize(original_img.copy(), (160, 160)) # увеличение размерности фото cap = cv2.VideoCapture(0) while True: grab, compared_img = cap.read() # уменьшение размера фото, чтобы сеть могла его обработать compared_img_copy = compared_img.copy() # увеличение размерности фото print("Сравниваем...") # сравнение исходного фото с кадром с камеры ver_result = DeepFace.verify(original_img, compared_img, distance_metric='euclidean', model_name='VGG-Face', detector_backend='opencv') cv2.imshow('Compared', compared_img) # вывод результата verified = bool(ver_result['verified']) if not verified: print("ИТОГ - Разные!") else: print("ИТОГ- Один и тот же") key = cv2.waitKey(1) & 0xFF if key == ord("q"): break cap.release() cv2.destroyAllWindows()
def verify_images(img1, img2, results): obj = DeepFace.verify(img1, img2, distance_metric='euclidean', model_name='OpenFace', detector_backend='opencv') results.append(obj)
def verify_Face(UserID): FrontPath = 'Users' + filesep + 'FaceData' + \ filesep + UserID + filesep + 'frontSide.jpeg' LeftPath = 'Users' + filesep + 'FaceData' + \ filesep + UserID + filesep + 'leftSide.jpeg' RightPath = 'Users' + filesep + 'FaceData' + \ filesep + UserID + filesep + 'rightSide.jpeg' TargetPath = 'Users' + filesep + 'FaceData' + \ filesep + UserID + filesep + 'verifySide.jpeg' if(!extract_face(FrontPath)) { retrun {'status':False,'Message':'Fake Upload - Front Imprint'} } if(!extract_face(LeftPath)) { retrun {'status':False,'Message':'Fake Upload - Left Imprint'} } if(!extract_face(RightPath)) { retrun {'status':False,'Message':'Fake Upload - Right Imprint'} } if(!extract_face(TargetPath)) { retrun {'status':False,'Message':'Fake Upload - Verify Imprint'} } results = DeepFace.verify([[TargetPath, FrontPath], [TargetPath, LeftPath], [ TargetPath, RightPath], ], enforce_detection=False, model_name='Facenet') return {'pair_1': results['pair_1']['distance'], 'pair_2': results['pair_2']['distance'], 'pair_3': resul ts['pair_3']['distance'],'status':True}
def extract_face_from_image(image_path,image_path_2, required_size=(224, 224),): image = plt.imread(image_path) detector = MTCNN() faces = detector.detect_faces(image) face_images = [] distancearray=[] min_dist=0.47 for face in faces: x1, y1, width, height = face['box'] x2, y2 = x1 + width, y1 + height face_boundary = image[y1:y2, x1:x2] face_image = Image.fromarray(face_boundary) face_image = face_image.resize(required_size) face_array = asarray(face_image) face_images.append(face_array) resp=DeepFace.verify(face_array,image_path_2,enforce_detection=False,model_name="VGG-Face") if(resp["distance"]<min_dist): min_dist=resp["distance"] for face in faces: x1, y1, width, height = face['box'] x2, y2 = x1 + width, y1 + height face_boundary = image[y1:y2, x1:x2] face_image = Image.fromarray(face_boundary) face_image = face_image.resize(required_size) face_array = asarray(face_image) face_images.append(face_array) resp=DeepFace.verify(face_array,image_path_2,enforce_detection=False,model_name="VGG-Face") distancearray.append(resp["distance"]) if(resp["distance"]==min_dist): image=cv.rectangle(image, (x1, y1), (x2, y2), (0, 225, 0), 1) thickness = 2 font=cv.FONT_HERSHEY_SIMPLEX fontScale = 0.45 color = (0, 225, 0) image = cv.putText(image, "%"+str(int(distance_to_prob(resp["distance"]))), (x1, y1-10), font,fontScale, color, thickness, cv.LINE_AA) else: image=cv.rectangle(image, (x1, y1), (x2, y2), (225, 0, 0), 1) thickness = 2 font=cv.FONT_HERSHEY_SIMPLEX fontScale = 0.5 color = (225, 0, 0) image = cv.putText(image, '', (x1, y1-10), font,fontScale, color, thickness, cv.LINE_AA) print(len(face_images)) return face_images,image
def photo_verification(): photo_path = 'C://Users//sawer//PycharmProjects//lab3//obama.jpg' original_img = cv2.imread(photo_path) original_img_copy = cv2.resize(original_img.copy(), (500, 500)) cv2.imshow('Original', original_img_copy) comp_path = 'C://Users//sawer//PycharmProjects//lab3//obama2.jpg' another_path = 'C://Users//sawer//PycharmProjects//lab3//photo.jpg' compared_img = cv2.imread(comp_path) another_img = cv2.imread(another_path) another_img = cv2.resize(another_img.copy(), (500, 500)) cv2.imshow('another', another_img) cv2.imshow('Compared', compared_img) try: ver_result = DeepFace.verify(photo_path, comp_path, distance_metric='euclidean', model_name='Facenet', detector_backend='ssd') # вывод результата verified = bool(ver_result['verified']) if not verified: print("Разные люди") else: print("Один и тот же человек") key = cv2.waitKey(1) & 0xFF except cv2.error as e: print(e) try: ver_result = DeepFace.verify(photo_path, another_path, distance_metric='euclidean', model_name='Facenet', detector_backend='ssd') # вывод результата verified = bool(ver_result['verified']) if not verified: print("Разные люди") else: print("Один и тот же человек") key = cv2.waitKey(1) & 0xFF except cv2.error as e: print(e)
def verify(): req = request.get_json() trx_id = uuid.uuid4() tic = time.time() #------------------------- model_name = "VGG-Face"; distance_metric = "cosine" if "model_name" in list(req.keys()): model_name = req["model_name"] if "distance_metric" in list(req.keys()): distance_metric = req["distance_metric"] instances = [] if "img" in list(req.keys()): raw_content = req["img"] #list for item in raw_content: #item is in type of dict instance = [] img1 = item["img1"]; img2 = item["img2"] validate_img1 = False if len(img1) > 11 and img1[0:11] == "data:image/": validate_img1 = True validate_img2 = False if len(img2) > 11 and img2[0:11] == "data:image/": validate_img2 = True if validate_img1 != True or validate_img2 != True: return jsonify({'success': False, 'error': 'you must pass both img1 and img2 as base64 encoded string'}), 205 instance.append(img1); instance.append(img2) instances.append(instance) #-------------------------- if len(instances) == 0: return jsonify({'success': False, 'error': 'you must pass at least one img object in your request'}), 205 print("Input request of ", trx_id, " has ",len(instances)," pairs to verify") #-------------------------- resp_obj = DeepFace.verify(instances, model_name = model_name, distance_metric = distance_metric) #resp_obj = json.loads("{\"success\": true}") toc = time.time() resp_obj["trx_id"] = trx_id resp_obj["seconds"] = toc-tic #-------------------------- return resp_obj, 200
def verify_face(img1, img2): result = DeepFace.verify(img1, img2, distance_metric='euclidean', model_name='VGG-Face', detector_backend='opencv') verified = bool(result['verified']) if not verified: print('Разные люди (но это не точно)') else: print('На фото один и тот же человек (но это не точно)')
def verification(img1, img2, model_name = "VGG-Face", distance_metric = "cosine"): start = time.time() result = DeepFace.verify(img1, img2, model_name=model_name, distance_metric=distance_metric) print(result) demography = DeepFace.analyze(img1, ['age', 'gender', 'emotion']) print(demography) end = time.time() print("Total time taken : ", end - start)
def verify(reference_img_path, img_path): try: result = DeepFace.verify(reference_img_path, img_path, enforce_detection=False, model_name='VGG-Face') except AttributeError as e: # case when input image is a pdf, then the package can not read it. log.info(e) result = {"verified": False} if not result["verified"]: os.remove(img_path) return 0 else: return 1
def facematch(livpath, cardpath): key_list = [] resultdic = {} #,"OpenFace","DeepFace","Facenet" metrics = ["cosine", "euclidean", "euclidean_l2"] models = ["VGG-Face", "Dlib"] for model in models: for metric in metrics: result = DeepFace.verify(livpath, cardpath, model_name=model, distance_metric=metric) resultdic[model + ',' + metric] = result res = resultdic return res
def verify(img1_path, img2_path): img1 = cv2.imread(img1_path) img2 = cv2.imread(img2_path) plt.imshow(img1[:, :, ::-1]) plt.show() plt.imshow(img2[:, :, ::-1]) plt.show() result = DeepFace.verify(img1_path, img2_path, model_name="VGG-Face") print("result: ", result) verification = result["verified"] if verification: print("They are same !") else: print("They are not same !")
async def verification_route(file: List[bytes] = File(...)): image1 = Image.open(io.BytesIO(file[0])) img1 = tf.keras.preprocessing.image.img_to_array(image1) image2 = Image.open(io.BytesIO(file[1])) img2 = tf.keras.preprocessing.image.img_to_array(image2) # save to database instance = compare() instance.first.put(io.BytesIO(file[0])) instance.second.put(io.BytesIO(file[1])) instance.save() with graph.as_default(): result = DeepFace.verify(img1, img2, model_name="Facenet") return {"result": result}
def pipe(face_img, doc_img, verification, analysis): #analysis_models = {} #verification_model = {} verification_model = verification analysis_models = analysis #verification_model['FbDeepFace'] = FbDeepFace.loadModel() #analysis_models["age"] = Age.loadModel() #analysis_models["gender"] = Gender.loadModel() face_img = cv2.imread(face_img) doc_img = cv2.imread(doc_img) match = DeepFace.verify(face_img, doc_img, model_name = "FbDeepFace", model = verification_model['FbDeepFace']) if match['distance'] <= 0.55: analysis = DeepFace.analyze(face_img, actions=['age', 'gender'], models=analysis_models) age = analysis['age'] gender = analysis['gender'] return age, gender
def video_verification(): # faces/me.jpg photo_path = input( "Please provide a full path to the photo for comparison:\n") print("Loading...") original_img = cv2.imread(photo_path) original_img_copy = cv2.resize(original_img.copy(), (500, 500)) cv2.imshow('Original image', original_img_copy) # уменьшение размера фото, чтобы сеть могла его обработать original_img = cv2.resize(original_img.copy(), (160, 160)) # увеличение размерности фото original_img = np.expand_dims(original_img, axis=0) cap = cv2.VideoCapture(0) while True: grab, compared_img = cap.read() # уменьшение размера фото, чтобы сеть могла его обработать compared_img = cv2.resize(compared_img.copy(), (160, 160)) compared_img_copy = compared_img.copy() # увеличение размерности фото compared_img = np.expand_dims(compared_img, axis=0) print("Verifying two images...") # сравнение исходного фото с кадром с камеры ver_result = DeepFace.verify(original_img, compared_img, distance_metric='euclidean', model_name='Facenet', detector_backend='ssd') cv2.imshow('Compared image', compared_img_copy) # вывод результата verified = bool(ver_result['verified']) if not verified: print("[RESULT] - These are different persons!") else: print("[RESULT]- Same person") key = cv2.waitKey(1) & 0xFF if key == ord("q"): print("[INFO] process finished by user") break cap.release() cv2.destroyAllWindows()
pretrained_models["DeepFace"] = FbDeepFace.loadModel() print("FbDeepFace loaded") pretrained_models["DeepID"] = DeepID.loadModel() print("DeepID loaded") instances = df[["file_x", "file_y"]].values.tolist() models = ['VGG-Face'] metrics = ["cosine"] if True: for model in models: for metric in metrics: resp_obj = DeepFace.verify(instances, model_name=model, model=pretrained_models[model], distance_metric=metric) distances = [] for i in range(0, len(instances)): distance = round(resp_obj["pair_%s" % (i + 1)]["distance"], 4) distances.append(distance) df['%s_%s' % (model, metric)] = distances df.to_csv("face-recognition-pivot.csv", index=False) else: df = pd.read_csv("face-recognition-pivot.csv") df_raw = df.copy()
def verifyWrapper(req, trx_id = 0): resp_obj = jsonify({'success': False}) model_name = "VGG-Face"; distance_metric = "cosine" if "model_name" in list(req.keys()): model_name = req["model_name"] if "distance_metric" in list(req.keys()): distance_metric = req["distance_metric"] #---------------------- instances = [] if "img" in list(req.keys()): raw_content = req["img"] #list for item in raw_content: #item is in type of dict instance = [] img1 = item["img1"]; img2 = item["img2"] validate_img1 = False if len(img1) > 11 and img1[0:11] == "data:image/": validate_img1 = True validate_img2 = False if len(img2) > 11 and img2[0:11] == "data:image/": validate_img2 = True if validate_img1 != True or validate_img2 != True: return jsonify({'success': False, 'error': 'you must pass both img1 and img2 as base64 encoded string'}), 205 instance.append(img1); instance.append(img2) instances.append(instance) #-------------------------- if len(instances) == 0: return jsonify({'success': False, 'error': 'you must pass at least one img object in your request'}), 205 print("Input request of ", trx_id, " has ",len(instances)," pairs to verify") #-------------------------- if model_name == "VGG-Face": resp_obj = DeepFace.verify(instances, model_name = model_name, distance_metric = distance_metric, model = vggface_model) elif model_name == "Facenet": resp_obj = DeepFace.verify(instances, model_name = model_name, distance_metric = distance_metric, model = facenet_model) elif model_name == "OpenFace": resp_obj = DeepFace.verify(instances, model_name = model_name, distance_metric = distance_metric, model = openface_model) elif model_name == "DeepFace": resp_obj = DeepFace.verify(instances, model_name = model_name, distance_metric = distance_metric, model = deepface_model) elif model_name == "x": resp_obj = DeepFace.verify(instances, model_name = modxel_name, distance_metric = distance_metric, model = deepid_model) elif model_name == "ArcFace": resp_obj = DeepFace.verify(instances, model_name = model_name, distance_metric = distance_metric, model = arcface_model) elif model_name == "Ensemble": models = {} models["VGG-Face"] = vggface_model models["Facenet"] = facenet_model models["OpenFace"] = openface_model models["DeepFace"] = deepface_model resp_obj = DeepFace.verify(instances, model_name = model_name, model = models) else: resp_obj = jsonify({'success': False, 'error': 'You must pass a valid model name. You passed %s' % (model_name)}), 205 return resp_obj
# Save output of the function. filename = output_name.format(os.getpid()) cv2.imwrite(filename, processed_img) # Check the output of face_detect function. img_path = '/content/drive/My Drive/IMG_20201007_200043.jpg' output_name = 'pan_img.jpg' pan = face_detect(img_path, output_name) # Check the output of face_detect function. img_path = '/content/drive/My Drive/IMG20201010221637.jpg' output_name = 'clicked_img.jpg' orig = face_detect(img_path, output_name) #### Resize the image because output of face_detect func will be scaled according #### to original image but for verification size of both the images should be #### same(PAN card image is little squeezed, resizing will solve that issue). def resize_img(path, size): img = cv2.imread(path) img = cv2.resize(img, (size, size)) return img clicked_img = resize_img('/content/clicked_img.jpg', 512) pan_img = resize_img('/content/pan_img.jpg', 512) # Set enforce_detection False: Face could not be detected. Please confirm that the picture # is a face photo or consider to set enforce_detection param to False. result = DeepFace.verify(clicked_img, pan_img, enforce_detection = False) print("Is verified: ", result["verified"])
from deepface import DeepFace import os import cv2 img1_path = 'image/ping_1.png' img2_path = 'image/Oak_3.png' img_1 = cv2.imread(img1_path) img_2 = cv2.imread(img2_path) result = DeepFace.verify(img1_path, img2_path, model_name = 'ArcFace') print(result)
# resize pixels to the model size face_image = Image.fromarray(face_boundary) face_image = face_image.resize(required_size) face_array = asarray(face_image) face_images.append(face_array) return face_images extracted_face = extract_face_from_image('kaushiki2.jpg') #Display the face from the extracted faces plt.imshow(extracted_face[0]) plt.show() #Compare the single/Multiple faces in two images from deepface import DeepFace import cv2 from matplotlib import pyplot as plt img1 = cv2.imread("women.jpg") plt.imshow(img1[:, :, ::-1]) plt.show() img2 = cv2.imread("5 women.jpg") plt.imshow(img2[:, :, ::-1]) plt.show() result = DeepFace.verify(img1, img2) print("Is same face", result["verified"])
def verify(): global graph tic = time.time() req = request.get_json() trx_id = uuid.uuid4() resp_obj = jsonify({'success': False}) with graph.as_default(): model_name = "VGG-Face" distance_metric = "cosine" if "model_name" in list(req.keys()): model_name = req["model_name"] if "distance_metric" in list(req.keys()): distance_metric = req["distance_metric"] #---------------------- instances = [] if "img" in list(req.keys()): raw_content = req["img"] #list for item in raw_content: #item is in type of dict instance = [] img1 = item["img1"] img2 = item["img2"] validate_img1 = False if len(img1) > 11 and img1[0:11] == "data:image/": validate_img1 = True validate_img2 = False if len(img2) > 11 and img2[0:11] == "data:image/": validate_img2 = True if validate_img1 != True or validate_img2 != True: return jsonify({ 'success': False, 'error': 'you must pass both img1 and img2 as base64 encoded string' }), 205 instance.append(img1) instance.append(img2) instances.append(instance) #-------------------------- if len(instances) == 0: return jsonify({ 'success': False, 'error': 'you must pass at least one img object in your request' }), 205 print("Input request of ", trx_id, " has ", len(instances), " pairs to verify") #-------------------------- if model_name == "VGG-Face": resp_obj = DeepFace.verify(instances, model_name=model_name, distance_metric=distance_metric, model=vggface_model) elif model_name == "Facenet": resp_obj = DeepFace.verify(instances, model_name=model_name, distance_metric=distance_metric, model=facenet_model) elif model_name == "OpenFace": resp_obj = DeepFace.verify(instances, model_name=model_name, distance_metric=distance_metric, model=openface_model) elif model_name == "DeepFace": resp_obj = DeepFace.verify(instances, model_name=model_name, distance_metric=distance_metric, model=deepface_model) elif model_name == "Ensemble": models = {} models["VGG-Face"] = vggface_model models["Facenet"] = facenet_model models["OpenFace"] = openface_model models["DeepFace"] = deepface_model resp_obj = DeepFace.verify(instances, model_name=model_name, model=models) else: return jsonify({ 'success': False, 'error': 'You must pass a valid model name. Available models are VGG-Face, Facenet, OpenFace, DeepFace but you passed %s' % (model_name) }), 205 #-------------------------- toc = time.time() resp_obj["trx_id"] = trx_id resp_obj["seconds"] = toc - tic return resp_obj, 200
from deepface import DeepFace result = DeepFace.verify( r"C:\Users\bitcamp\Desktop\opencv_dnn_202005\image\ujung.jpg") print("Is verified: ", result["verified"]) print()
def test_cases(): print("DeepFace.detectFace test") 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") print("-----------------------------------------") img_path = "dataset/img1.jpg" embedding = DeepFace.represent(img_path) print("Function returned ", len(embedding), "dimensional vector") evaluate(len(embedding) > 0) print("-----------------------------------------") print("Face detectors test") for detector in detectors: print(detector + " detector") res = DeepFace.verify(dataset[0][0], dataset[0][1], detector_backend=detector) print(res) assert res["verified"] == dataset[0][2] print("-----------------------------------------") print("Find function test") df = DeepFace.find(img_path="dataset/img1.jpg", db_path="dataset") print(df.head()) evaluate(df.shape[0] > 0) print("-----------------------------------------") print("Facial analysis test. Passing nothing as an action") img = "dataset/img4.jpg" demography = DeepFace.analyze(img) print(demography) evaluate(demography["age"] > 20 and demography["age"] < 40) evaluate(demography["dominant_gender"] == "Woman") print("-----------------------------------------") print("Facial analysis test. Passing all to the action") demography = DeepFace.analyze(img, ['age', 'gender', 'race', 'emotion']) print("Demography:") print(demography) #check response is a valid json print("Age: ", demography["age"]) print("Gender: ", demography["dominant_gender"]) print("Race: ", demography["dominant_race"]) print("Emotion: ", demography["dominant_emotion"]) evaluate(demography.get("age") is not None) evaluate(demography.get("dominant_gender") is not None) evaluate(demography.get("dominant_race") is not None) evaluate(demography.get("dominant_emotion") is not None) print("-----------------------------------------") print( "Facial analysis test 2. Remove some actions and check they are not computed" ) demography = DeepFace.analyze(img, ['age', 'gender']) print("Age: ", demography.get("age")) print("Gender: ", demography.get("dominant_gender")) print("Race: ", demography.get("dominant_race")) print("Emotion: ", demography.get("dominant_emotion")) evaluate(demography.get("age") is not None) evaluate(demography.get("dominant_gender") is not None) evaluate(demography.get("dominant_race") is None) evaluate(demography.get("dominant_emotion") is None) print("-----------------------------------------") print("Facial recognition tests") for model in models: for metric in metrics: for instance in dataset: img1 = instance[0] img2 = instance[1] result = instance[2] resp_obj = DeepFace.verify(img1, img2, model_name=model, distance_metric=metric) prediction = resp_obj["verified"] distance = round(resp_obj["distance"], 2) threshold = resp_obj["threshold"] passed = prediction == result evaluate(passed) if passed: test_result_label = "passed" else: test_result_label = "failed" if prediction == True: classified_label = "verified" else: classified_label = "unverified" 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("--------------------------") # ----------------------------------------- print("Passing numpy array to analyze function") img = cv2.imread("dataset/img1.jpg") resp_obj = DeepFace.analyze(img) print(resp_obj) evaluate(resp_obj["age"] > 20 and resp_obj["age"] < 40) evaluate(resp_obj["gender"] == "Woman") 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) evaluate(res["verified"] == True) print("--------------------------") print("Passing numpy array to find function") img1 = cv2.imread("dataset/img1.jpg") df = DeepFace.find(img1, db_path="dataset") print(df.head()) evaluate(df.shape[0] > 0) print("--------------------------") print("non-binary gender tests") #interface validation - no need to call evaluate here for img1_path, img2_path, verified in dataset: for detector in detectors: result = DeepFace.analyze(img1_path, actions=('gender', ), detector_backend=detector, enforce_detection=False) print(result) assert 'gender' in result.keys() assert 'dominant_gender' in result.keys( ) and result["dominant_gender"] in ["Man", "Woman"] if result["dominant_gender"] == "Man": assert result["gender"]["Man"] > result["gender"]["Woman"] else: assert result["gender"]["Man"] < result["gender"]["Woman"]
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' #----------------------------------------- print("Bulk tests") print("-----------------------------------------") print("Bulk face recognition tests") dataset = [['dataset/img1.jpg', 'dataset/img2.jpg', True], ['dataset/img5.jpg', 'dataset/img6.jpg', True]] resp_obj = DeepFace.verify(dataset) print(resp_obj["pair_1"]["verified"] == True) print(resp_obj["pair_2"]["verified"] == True) print("-----------------------------------------") print("Bulk facial analysis tests") dataset = [ 'dataset/img1.jpg', 'dataset/img2.jpg', 'dataset/img5.jpg', 'dataset/img6.jpg' ] resp_obj = DeepFace.analyze(dataset) print(resp_obj["instance_1"]["age"], " years old ", resp_obj["instance_1"]["dominant_emotion"], " ",
# pred = [] # pair = all_pairs[i] # print(len(pair)) # """result = DeepFace.verify([pair], enforce_detection = False) # pred.append(result["pair_1"]["verified"])""" # try: # result = DeepFace.verify([pair]) # pred.append(result["pair_1"]["verified"]) # except ValueError: # pred.append(2) ### first line runs deepface with default vgg model and second line runs it with Facenet model models will be automaticly downloaded # result = DeepFace.verify(all_pairs, enforce_detection= False) result = DeepFace.verify(all_pairs, enforce_detection=False, model_name="Facenet") #print(result) ### write results to txt file with open("facenet_model_output.txt", "w") as file: for i in range(0, 4000): # for i in range(0,len(all_pairs[0:10])): file.write(str(result["pair_" + str(i + 1)]["verified"]) + "\n") # i = 1 # for res in result: # print(res) # file.write(str(res["pair_" + str(i)]["verified"]) + "\n") # i += 1 """"try:
import json import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' #----------------------------------------- print("Bulk tests") print("-----------------------------------------") print("Bulk face recognition tests") dataset = [['dataset/img1.jpg', 'dataset/img2.jpg', True], ['dataset/img5.jpg', 'dataset/img6.jpg', True]] resp_obj = DeepFace.verify(dataset) print(resp_obj["pair_1"]["verified"] == True) print(resp_obj["pair_2"]["verified"] == True) print("-----------------------------------------") print("Bulk facial analysis tests") dataset = [ 'dataset/img1.jpg', 'dataset/img2.jpg', 'dataset/img5.jpg', 'dataset/img6.jpg' ] resp_obj = DeepFace.analyze(dataset) print(resp_obj["instance_1"]["age"], " years old ", resp_obj["instance_1"]["dominant_emotion"], " ",
import tensorflow as tf from PIL import Image from io import BytesIO from deepface import DeepFace with open("main/test_image.png", "rb") as image: f = image.read() b = bytearray(f) img = Image.open(BytesIO(b)) image_array = tf.keras.preprocessing.image.img_to_array(img) # demography = DeepFace.analyze(image_array, actions=["emotion"]) demography = DeepFace.analyze(image_array, actions=["age", "gender", "race", "emotion"]) result = DeepFace.verify(image_array, image_array, model_name="Facenet") print("Is verified: ", result["verified"])
#!/usr/bin/env python # coding: utf-8 # # https://www.youtube.com/watch?v=f9aV2Jfd5fc # In[1]: # pip install deepface # In[2]: from deepface import DeepFace import cv2 # In[3]: image1 = cv2.imread('/home/hduser/jupyter/Face_Comparison_deepface/1.jpg') image2 = cv2.imread('/home/hduser/jupyter/Face_Comparison_deepface/2.jpg') # In[4]: DeepFace.verify(image1, image2)['verified'] # In[ ]:
#! /usr/bin/python3 from deepface import DeepFace import time tik = time.time() result = DeepFace.verify("katya1.jpg", "katya2.jpg", model_name='ArcFace', detector_backend='retinaface') # 'retinaface' print("Is verified: ", result["verified"], time.time() - tik)
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' #----------------------------------------- dataset = [ ['dataset/img1.jpg', 'dataset/img2.jpg', True], ['dataset/img1.jpg', 'dataset/img6.jpg', True] ] print("-----------------------------------------") print("Face detectors test") print("opencv detector") res = DeepFace.verify(dataset, detector_backend = 'opencv') print(res) print("ssd detector") res = DeepFace.verify(dataset, detector_backend = 'ssd') print(res) print("dlib detector") res = DeepFace.verify(dataset, detector_backend = 'dlib') print(res) print("mtcnn detector") res = DeepFace.verify(dataset, detector_backend = 'mtcnn') print(res) print("-----------------------------------------")
from deepface import DeepFace result = DeepFace.verify("face_images/Gates/1.jpg", "face_images/Gates/2.jpg") print(result)