From 4b489bf3626f3d57e510076edc91e5ca10df57d4 Mon Sep 17 00:00:00 2001 From: Siryuanshao Date: Sun, 6 Jan 2019 15:51:31 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BA=BA=E8=84=B8=E8=8E=B7=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 人脸识别/getface.py | 65 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 人脸识别/getface.py diff --git a/人脸识别/getface.py b/人脸识别/getface.py new file mode 100644 index 0000000..8db6b29 --- /dev/null +++ b/人脸识别/getface.py @@ -0,0 +1,65 @@ +# coding = utf-8 +# 圈出图片中所有的人脸 +import numpy as np +import math +import cv2 +import dlib + +path = '/Users/yanshao/Desktop/img/timg.jpeg' +Model = '/Users/yanshao/dlib/shape_predictor_5_face_landmarks.dat' + +# 首先把图片转化为方形 + +detector = dlib.get_frontal_face_detector() +predictor = dlib.shape_predictor(Model) + + +def preprocess(): + image = cv2.imread(path) + height, width, chl = image.shape[0], image.shape[1], image.shape[2] + rec = int(max(height, width) * 1.5) + pic = np.zeros((rec, rec, chl), np.uint8) + baseh, basew = (rec - height) // 2, (rec - width) // 2 + pic[baseh:height + baseh, basew:width + basew] = image + return pic, rec + + +# 为了检测出图片中的所有人脸,我们每次把图片翻转45度 +def get_dist(point1, point2): + return math.sqrt((point1[0]-point2[0])*(point1[0]-point2[0]) + + (point1[1]-point2[1])*(point1[1]-point2[1])) + + +def get_pos(point, M): + return np.linalg.solve([[M[0][0], M[0][1]], + [M[1][0], M[1][1]]], + [point[0]-M[0][2], point[1]-M[1][2]]).astype(np.int32) + + +pic, rec = preprocess() +center = (rec//2,rec//2) +list = [] +for ang in range(0, 8): + M = cv2.getRotationMatrix2D(center, 45*ang, 1) + pic2 = cv2.warpAffine(pic, M, (rec, rec)) + dets = detector(pic2, 1) + print(len(dets)) + for face in dets: + left, right, top, bot = face.left(), face.right(), face.top(), face.bottom() + LT, RB = get_pos((left, top), M), get_pos((right, bot), M) + list.append(((LT[0]+RB[0])//2, (LT[1]+RB[1])//2, (right-left)//2)) + + cv2.destroyAllWindows() + +length = len(list) +for i in range(0, length): + flag = False + for j in range(0, i): + if get_dist(list[i], list[j]) < list[i][2]+list[j][2]: + flag = True + if not flag: + cv2.circle(pic, (list[i][0], list[i][1]), list[i][2], (0, 255, 0)) + +cv2.imshow("img", pic) +cv2.waitKey(0) +cv2.destroyAllWindows()