Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
vardanagarwal
GitHub Repository: vardanagarwal/Proctoring-AI
Path: blob/master/face_spoofing.py
453 views
1
import numpy as np
2
import cv2
3
from sklearn.externals import joblib
4
from face_detector import get_face_detector, find_faces
5
6
def calc_hist(img):
7
"""
8
To calculate histogram of an RGB image
9
10
Parameters
11
----------
12
img : Array of uint8
13
Image whose histogram is to be calculated
14
15
Returns
16
-------
17
histogram : np.array
18
The required histogram
19
20
"""
21
histogram = [0] * 3
22
for j in range(3):
23
histr = cv2.calcHist([img], [j], None, [256], [0, 256])
24
histr *= 255.0 / histr.max()
25
histogram[j] = histr
26
return np.array(histogram)
27
28
face_model = get_face_detector()
29
clf = joblib.load('models/face_spoofing.pkl')
30
cap = cv2.VideoCapture(0)
31
32
sample_number = 1
33
count = 0
34
measures = np.zeros(sample_number, dtype=np.float)
35
36
while True:
37
ret, img = cap.read()
38
faces = find_faces(img, face_model)
39
40
measures[count%sample_number]=0
41
height, width = img.shape[:2]
42
for x, y, x1, y1 in faces:
43
44
roi = img[y:y1, x:x1]
45
point = (0,0)
46
47
img_ycrcb = cv2.cvtColor(roi, cv2.COLOR_BGR2YCR_CB)
48
img_luv = cv2.cvtColor(roi, cv2.COLOR_BGR2LUV)
49
50
ycrcb_hist = calc_hist(img_ycrcb)
51
luv_hist = calc_hist(img_luv)
52
53
feature_vector = np.append(ycrcb_hist.ravel(), luv_hist.ravel())
54
feature_vector = feature_vector.reshape(1, len(feature_vector))
55
56
prediction = clf.predict_proba(feature_vector)
57
prob = prediction[0][1]
58
59
measures[count % sample_number] = prob
60
61
cv2.rectangle(img, (x, y), (x1, y1), (255, 0, 0), 2)
62
63
point = (x, y-5)
64
65
# print (measures, np.mean(measures))
66
if 0 not in measures:
67
text = "True"
68
if np.mean(measures) >= 0.7:
69
text = "False"
70
font = cv2.FONT_HERSHEY_SIMPLEX
71
cv2.putText(img=img, text=text, org=point, fontFace=font, fontScale=0.9, color=(0, 0, 255),
72
thickness=2, lineType=cv2.LINE_AA)
73
else:
74
font = cv2.FONT_HERSHEY_SIMPLEX
75
cv2.putText(img=img, text=text, org=point, fontFace=font, fontScale=0.9,
76
color=(0, 255, 0), thickness=2, lineType=cv2.LINE_AA)
77
78
count+=1
79
cv2.imshow('img_rgb', img)
80
81
if cv2.waitKey(1) & 0xFF == ord('q'):
82
break
83
84
cap.release()
85
cv2.destroyAllWindows()
86
87