-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathface.py
59 lines (54 loc) · 1.97 KB
/
face.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
import cv2
from cv2 import imread
from cv2 import imshow
from cv2 import waitKey
from cv2 import destroyAllWindows
from cv2 import CascadeClassifier
from cv2 import rectangle
import urllib.request
import os
import numpy as np
import PIL.Image
class Face:
classifier = None
@classmethod
def get_face_bboxes(cls, pixels):
HAAR = "haarcascade_frontalface_default.xml"
if not os.path.isfile(HAAR):
HAAR_URL="https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml"
urllib.request.urlretrieve(HAAR_URL, "haarcascade_frontalface_default.xml")
assert(os.path.isfile(HAAR)), "Failed to download %s" % HAAR_URL
if not cls.classifier:
cls.classifier = CascadeClassifier(HAAR)
# bboxes = cls.classifier.detectMultiScale(pixels, scaleFactor=1.1)
gray = cv2.cvtColor(pixels, cv2.COLOR_BGR2GRAY)
bboxes = cls.classifier.detectMultiScale(gray,
scaleFactor = 1.1,
minSize = (36, 36))
return bboxes
@classmethod
def get_face_bboxes_from_pil_image(cls, pil_image):
opencvImage = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR)
return cls.get_face_bboxes(opencvImage)
@classmethod
def get_face_bboxes_from_file(cls, image_file):
pixels = imread(image_file)
return cls.get_face_bboxes(pixels)
def main():
test_file = "images/278.jpg"
pixels = imread(test_file)
# print(pixels)
bboxes = Face.get_face_bboxes(pixels)
print(bboxes)
for box in bboxes:
x, y, width, height = box
x2, y2 = x + width, y + height
rectangle(pixels, (x, y), (x2, y2), (0, 0, 255), 1)
# show the image
imshow('faces detection', pixels)
# keep the window open until we press a key
waitKey(0)
# close the window
destroyAllWindows()
if __name__ == "__main__":
main()