-
Notifications
You must be signed in to change notification settings - Fork 0
/
face_crop.py
83 lines (60 loc) · 1.69 KB
/
face_crop.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import os
import argparse
import dlib
import cv2
import imutils
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", type=str, default="",
help="path to input image file")
args = vars(ap.parse_args())
images = args["image"]
for fl in os.listdir(images):
print(fl)
if fl == ".DS_Store" or fl == "_DS_Store":
#print(fl)
print("stupid files")
else:
images2 = os.path.join(images,fl)
frame = cv2.imread(images2)
detector = dlib.get_frontal_face_detector()
try:
if len(frame) > 0:
#frame2 = imutils.resize(frame, width=450)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
detected_faces = detector(gray, 0)
height = frame.shape[0]
width = frame.shape[1]
height2 = gray.shape[0]
face_rect = detected_faces[0]
a = face_rect.left()
b = face_rect.top()
c = face_rect.right()
d = face_rect.bottom()
#print(a,b,c,d)
if(face_rect.left() < 0):
a = 0
if(face_rect.top() < 0):
b = 0
if(face_rect.right() > width):
c = width-1
if(face_rect.bottom() > height):
d = height-1
#print(a,b,c,d)
face = frame[b:d , a:c]
fl2 = fl.split(".")[0]
# cv2.imwrite( "cropped" + ".jpg",face)
# cropped = cv2.resize(face,(300,300))
# cv2.imwrite( str(fl) + ".jpg",cropped)
cv2.imwrite( str(images) + "/" + str(fl2) + "_crop.jpg",face)
# ratio = height*width/((c-a)*(d-b))
# print(ratio)
# a1 = int(a*width/450)
# b1 = int(b*height/height2)
# c1 = int(c*width/450)
# d1 = int(d*height/height2)
# face2 = frame[b1:d1 , a1:c1]
# cv2.imwrite( "cropped1" + ".jpg",face2)
except:
os.remove(images2)
print("not cropped, so deleting:", fl)
continue