-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcrop_face.py
53 lines (40 loc) · 1.51 KB
/
crop_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
##################################################################
# This script crop faces from a folder contains many human figures
##################################################################
import sys
import dlib
import cv2
import os
Images_Folder = 'train/me'
OutFace_Folder = 'train/me_face/'
Images_Path = os.path.join(os.path.realpath('.'), Images_Folder)
pictures = os.listdir(Images_Path)
detector = dlib.get_frontal_face_detector()
print(pictures)
def rotate(img):
rows,cols,_ = img.shape
M = cv2.getRotationMatrix2D((cols / 2, rows / 2), -90, 1)
dst = cv2.warpAffine(img, M, (cols, rows))
return dst
for f in pictures:
img = cv2.imread(os.path.join(Images_Path,f), cv2.IMREAD_COLOR)
b, g, r = cv2.split(img)
img2 = cv2.merge([r, g, b])
img = rotate(img)
dets = detector(img, 1)
#print("Number of faces detected: {}".format(len(dets)))
for idx, face in enumerate(dets):
# print('face{}; left{}; top {}; right {}; bot {}'.format(idx, face.left(). face.top(), face.right(), face.bottom()))
left = face.left()
top = face.top()
right = face.right()
bot = face.bottom()
#print(left, top, right, bot)
#cv2.rectangle(img, (left, top), (right, bot), (0, 255, 0), 3)
#print(img.shape)
crop_img = img[top:bot, left:right]
#cv2.imshow(f, img)
#cv2.imshow(f, crop_img)
cv2.imwrite(OutFace_Folder+f[:-4]+"_face.jpg", crop_img)
#k = cv2.waitKey(1000)
#cv2.destroyAllWindows()