Skip to content

Instantly share code, notes, and snippets.

@kingsj0405
Created March 21, 2019 03:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kingsj0405/d6b3ab8a3c0288b6d073e6361052afbf to your computer and use it in GitHub Desktop.
Save kingsj0405/d6b3ab8a3c0288b6d073e6361052afbf to your computer and use it in GitHub Desktop.
Compare face image
"""
This program is wrapper of face_recognition on the following link
https://github.com/ageitgey/face_recognition
You need to install followings
- Python3.3+ or Python2.7
- dlib
- face_recognition
For more information visit ageithey/face_recognition
Usage:
You can only use this with import functions
Also, you can check how to use functions on `CompareFaceTest`
Test:
python compare-face.py
"""
import face_recognition
import unittest
from os import listdir
from os.path import join
def compare_with_file_path(path1, path2):
"""Get distance of two face image with file paths.
Support bmp, jpg, png
Args:
path1 (str): first image path to compare
path2 (str): second image path to compare
Returns:
int: The distance of two image
"""
known_image = face_recognition.load_image_file(path1)
unknown_image = face_recognition.load_image_file(path2)
biden_encoding = face_recognition.face_encodings(known_image)[0]
unknown_encoding = face_recognition.face_encodings(unknown_image)[0]
results = face_recognition.face_distance([biden_encoding], unknown_encoding)
return results[0]
def compare_with_directory_path(path1, path2):
"""Get distances of multiple images with directory paths.
This compare the images with same name on each directory. For example,
directory1/a.jpg(compared) directory2/a.jpg(compared)
directory1/b.jpg(not compared)
directory2/c.jpb(not compared)
directory1/d.jpg(compared) directory2/d.jpg(compared)
Support bmp, jpg, png
Args:
path1 (str): first directory path to compare
path2 (str): second directory path to compare
Returns:
list: (file_name, distance) of each matched image
"""
file_paths1 = listdir(path1)
file_paths2 = listdir(path2)
common_paths = list(set(file_paths1) & set(file_paths2))
results = []
for fp in common_paths:
result = compare_with_file_path(join(path1, fp), join(path2, fp))
results.append((fp, result))
return results
class CompareFaceTests(unittest.TestCase):
def test_compare_with_file_path(self):
dist = compare_with_file_path("images/1_1.jpg", "images/1_3.jpg")
print("test_compare_with_file_path")
print("=" * 10 + "print start" + "=" * 10)
print(dist)
print("=" * 11 + "print end" + "=" * 11)
def test_compare_with_file_directory(self):
dists = compare_with_directory_path("images/origin", "images/aged")
print("test_compare_with_file_directory")
print("=" * 10 + "print start" + "=" * 10)
for d in dists:
print(d)
print("=" * 11 + "print end" + "=" * 11)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment