-
Notifications
You must be signed in to change notification settings - Fork 1
/
probability.py
34 lines (26 loc) · 1.15 KB
/
probability.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
import cv2
def probability(imgpath):
# load pre-trained Haar cascade for face detection
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# read input image
img = cv2.imread(imgpath)
# convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# detect faces in the grayscale image
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)
# create an array to store probabilities of having a face
face_probs = []
# loop over detected faces and calculate probabilities
for (x,y,w,h) in faces:
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
# calculate probability by counting non-zero pixels in the grayscale ROI
face_prob = cv2.countNonZero(roi_gray) / (roi_gray.shape[0] * roi_gray.shape[1])
face_probs.append(face_prob)
# calculate the final probability as the maximum probability in the face_probs array
if len(face_probs) > 0:
final_probab = int(max(face_probs) * 100)
else:
final_probab = 0
# return the final probability
return final_probab