dlib实现,需要shape_predictor_68_face_landmarks.dat模型
# 读帧
videoCapture = cv2.VideoCapture(videoName)
date = time.strftime("%Y-%m-%d %H:%M:%S")
# 计数
i = 0
print('{} save image start'.format(videoName))
while True:
success, img = videoCapture.read()
try:
if success:
i = i + 1
# save_image(img, savePath + "_" + str(i))
# 旋转图片
if angle > 0:
img = imutils.rotate_bound(img, angle)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
dets = detector(gray, 1)
for face in dets:
shape = predictor(img, face)
chang = []
kuan = []
# 遍历所有点,打印出其坐标,并圈出来
for pt in shape.parts():
chang.append(pt.x)
kuan.append(pt.y)
# 调节人像大小
x1, x2 = max(chang) + 60, min(chang) - 65
minSize = min(kuan)
y1, y2 = max(kuan) + 100, minSize - (minSize - 20)
cropped = img[y2 + 1:y1, x2 + 1:x1]
cropped = cv2.resize(cropped, (IMAGE_SIZE, IMAGE_SIZE), cv2.INTER_CUBIC)
cv2.imwrite(savePath + "_" + str(i) + '.jpg', cropped)
print(date + " "+ savePath + "_" + str(i) + '.jpg')
else:
print('{} {} total {} images'.format(date, videoName, i))
print('{} {} image save end'.format(date, videoName))
break
except Exception as e:
continue
videoCapture.release()
cv2.destroyAllWindows()
opencv实现抠图,需要haarcascade_frontalface_alt2.xml模型
cap = cv2.VideoCapture(path)
classfier = cv2.CascadeClassifier("./model/haarcascade_frontalface_alt2.xml")
suc = cap.isOpened() # 是否成功打开
frame_count = 0
out_count = 0
while suc:
frame_count += 1
if out_count > 5: # 最多取出多少张
break
suc, frame = cap.read() # 读取一帧
# grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faceRects = classfier.detectMultiScale(frame, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32)) # 读取脸部位置
if len(faceRects) > 0: # 大于0则检测到人脸
for faceRect in faceRects: # 单独框出每一张人脸
x, y, w, h = faceRect
image = frame[y - 10: y + h + 10, x - 10: x + w + 10]
# image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 转为灰度图
img_new = cv2.resize(image, (64, 64), interpolation=cv2.INTER_CUBIC) # 处理面部的大小
cv2.imwrite('./data/%d.jpg' % out_count, img_new,[95]) # 存储到指定目录
out_count += 1
print('成功提取的第%d个脸部' % out_count)
break # 每帧只获取一张脸,删除这个即为读出全部面部
cap.release()
cv2.destroyAllWindows()



