-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalgorithm.py
86 lines (67 loc) · 2.37 KB
/
algorithm.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
import face_recognition
import numpy as np
from person import Person
from PIL import Image
import cv2
THRESHOLD_NORMALIZER = float(42.5)
THRESHOLD_WEIGHT = float(1.0)
MIN_IMAGE_HEIGHT = 10
MIN_IMAGE_WIDTH = 10
def isImageValid(height, width):
return ((height >= MIN_IMAGE_HEIGHT) and (width >= MIN_IMAGE_WIDTH))
def read_image_from_disk(name):
return face_recognition.load_image_file("data/" + name)
def getSumIndex(encoding):
return np.sqrt(np.sum(encoding**2))
def threshold(val):
val = THRESHOLD_WEIGHT + (val/THRESHOLD_NORMALIZER)
return val
# return 1
def getEncoding(image, sharpness, image_size):
encoding = face_recognition.face_encodings(image,
known_face_locations=[(0,image_size[0], image_size[1],0)])
# encoding = face_recognition.face_encodings(image)
# print "encoding: ", encoding
if len(encoding) == 0:
return None
encoding = encoding[0]
encoding = np.array(encoding)
thresh = threshold(sharpness)
return encoding*thresh
def getPilImage(image):
array = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
pil_image = Image.fromarray(array)
return pil_image
def get_sharpness(pil_image):
pil_image = pil_image.convert('L')
array = np.asarray(pil_image, dtype=np.int32)
gy, gx = np.gradient(array)
gnorm = np.sqrt(gx**2 + gy**2)
sharpness = np.average(gnorm)
return float(sharpness)
def getFaces(image, timestamp):
faces = face_recognition.face_locations(image)
person_list = list()
for location in faces:
top, right, bottom, left = location
# print "Face Location {} {} {} {}".format(top,right,bottom,left)
face_image = image[top:bottom, left:right]
pil_image = getPilImage(face_image)
width, height = pil_image.size
if not isImageValid(height, width):
continue
'''Calculating Params'''
face_sharpness = get_sharpness(pil_image)
# TODO: Pass the known face locations for better accuracy
face_encoding = getEncoding(face_image, face_sharpness, [width, height])
if face_encoding is None:
# print "Face Encoding Failed"
continue
face_sum_index = getSumIndex(face_encoding)
person = Person(sharpness=face_sharpness, sum_index=face_sum_index,
encodings=face_encoding, pil_image=pil_image, timestamp=timestamp,
img_array=face_image)
person_list.append(person)
return person_list
def compare(encoding, matching_list_of_encodings):
return face_recognition.compare_faces(matching_list_of_encodings, encoding)