-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathdetect_face.py
46 lines (36 loc) · 1.3 KB
/
detect_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
from random import randint
import cv2
import sys
import os
import traceback
CASCADE="Face_cascade.xml"
FACE_CASCADE=cv2.CascadeClassifier(CASCADE)
def detect_faces(image_path,display=True):
image=cv2.imread(image_path)
image_grey=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
faces = FACE_CASCADE.detectMultiScale(image_grey,scaleFactor=1.16,minNeighbors=5,minSize=(25,25),flags=0)
for x,y,w,h in faces:
sub_img=image[y-10:y+h+10,x-10:x+w+10]
os.chdir("Extracted")
cv2.imwrite(str(randint(0,10000))+".jpg",sub_img)
os.chdir("../")
cv2.rectangle(image,(x,y),(x+w,y+h),(255, 255,0),2)
if display:
cv2.imshow("Faces Found",image)
# if (cv2.waitKey(0) & 0xFF == ord('q')) or (cv2.waitKey(0) & 0xFF == ord('Q')):
# cv2.destroyAllWindows()
if __name__ == "__main__":
if not "Extracted" in os.listdir("."):
os.mkdir("Extracted")
if len(sys.argv) < 2:
print("Usage: python Detect_face.py 'image path'")
sys.exit()
if os.path.isdir(sys.argv[1]):
for image in os.listdir(sys.argv[1]):
try:
print ("Processing.....",os.path.abspath(os.path.join(sys.argv[1],image)))
detect_faces(os.path.abspath(os.path.join(sys.argv[1],image)),False)
except Exception:
print ("Could not process ",os.path.abspath(os.path.join(sys.argv[1],image)))
else:
detect_faces(sys.argv[1])