-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcrop_image.py
64 lines (54 loc) · 1.85 KB
/
crop_image.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
# -*- coding: utf-8 -*
import os
import dlib
import numpy as np
import cv2
predictor_path = "shape_predictor_68_face_landmarks.dat"
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)
def get_landmarks(img):
dets = detector(img, 1)
landmarks = np.zeros((17,2))
for k, d in enumerate(dets):
shape = predictor(img, d)
landmarks[0] = (shape.part(48).x, shape.part(48).y)
for i in range(6):
landmarks[1+i] = (shape.part(59-i).x, shape.part(59-i).y)
for i in range(10):
landmarks[7+i] = (shape.part(26-i).x, shape.part(26-i).y)
return landmarks
def inside(X,Y,Region):
j=len(Region)-1
flag=False
for i in range(len(Region)):
if (Region[i][1]<Y and Region[j][1]>=Y or Region[j][1]<Y and Region[i][1]>=Y):
if (Region[i][0] + (Y - Region[i][1]) / (Region[j][1] - Region[i][1]) * (Region[j][0] - Region[i][0]) < X):
flag =not flag
j=i
return flag
def gen_mask(picpath, savepath):
paths = []
print('图片的路径:', picpath)
for root, dirs, files in os.walk(picpath):
for f in files:
paths.append(os.path.join(root, f))
num = 1
for path in paths:
print("processing image =========>")
print(num)
img = cv2.imread(path)
region = get_landmarks(img)
shape = list(img.shape)
img1 = img.copy()
for i in range(shape[0]):
for j in range(shape[1]):
if not inside(j, i, region):
img1[i, j] = (0, 0, 0)
else:
img1[i, j] = (255, 255, 255)
if not os.path.exists(savepath):
os.makedirs(savepath)
cv2.imwrite(savepath + '\\' + path.split('\\')[-1], img1)
num += 1
if __name__ == '__main__':
gen_mask()