-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathface_detect.py
59 lines (54 loc) · 1.95 KB
/
face_detect.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
import sys
import string
import PIL.Image
import io
import requests
import os
import time
import numpy
count = 0
class ImageHander(object):
def __init__(self, cascPath):
self.faceCascade = cv2.CascadeClassifier(cascPath)
def handerImage(self, url, dirPath, imgType):
print(url)
if imgType == 'gif' :
print('gif file can\'t be handered !')
return
try:
file = io.BytesIO(requests.get(url, timeout=10).content)
image = PIL.Image.open(file)
image = numpy.array(image)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = self.faceCascade.detectMultiScale(
gray,
scaleFactor=1.3,
minNeighbors=5,
minSize=(30, 30),
flags = cv2.CASCADE_SCALE_IMAGE
)
print("Found {0} faces!".format(len(faces)))
global count
for (x, y, w, h) in faces:
crop = image[y:y+h,x:x+w]
count = count + 1
name = time.strftime("%Y%m%d%H%M%S", time.localtime())
newfile = os.path.join(dirPath, name + str(count)+'.'+ imgType)
print(newfile)
try:
cv2.imwrite(newfile, crop)
except Exception as e:
print('file imwrite fail !')
if __name__ == '__main__':
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow("Faces found", image)
cv2.waitKey(0)
except Exception as e:
return
if __name__ == '__main__':
imageHander = ImageHander('haarcascade_frontalface_default.xml')
imageHander.handerImage('http://img.ishuo.cn/1609/1474689789.jpg', 'happy', 'jpg')
### Draw a rectangle around the faces