import os
import numpy as np
import dlib
import cv2
predictor_path = "shape_predictor_68_face_landmarks.dat"
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)
# 用imread读取图片后,调用get_landmarks(img)获取我们所要的人脸区域,代码如下:
def get_landmarks(img):
dets = detector(img, 1)
landmarks = np.zeros((19,2))
for k, d in enumerate(dets):
shape = predictor(img, d)
for i in range(19):
landmarks[i] = (shape.part(i).x, shape.part(i).y)
landmarks[17] = (shape.part(24).x, shape.part(24).y)
landmarks[18] = (shape.part(19).x, shape.part(19).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
if __name__=='__main__':
path='C:/PY2021/OPENCV4/face_detection/After_test/'
for filename in os.listdir(path):
img = cv2.imread(path+filename)
region = get_landmarks(img)
print (img.shape)
shape = list(img.shape) + [3] # 将图像转化为列表,便于访问
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)
cv2.imwrite("C:/PY2021/OPENCV4/face_detection/removeBG_23/" + str(filename), img1)
把49行代码 往右边移动2个层次, 要在第一个for 循环内
if __name__=='__main__':
path='C:/PY2021/OPENCV4/face_detection/After_test/'
for filename in os.listdir(path):
img = cv2.imread(path+filename)
region = get_landmarks(img)
print (img.shape)
shape = list(img.shape) + [3] # 将图像转化为列表,便于访问
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)
cv2.imwrite("C:/PY2021/OPENCV4/face_detection/removeBG_23/" + str(filename), img1)