コード例 #1
0
def crop_pic(onset_path, apex_path, onset_save_path, apex_save_path, flow_save_path):
    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')

    onset_image = cv2.imread(onset_path, 1)
    apex_image = cv2.imread(apex_path, 1)

    onset_det = detector(onset_image, 1)[0]
    apex_det = detector(apex_image, 1)[0]

    onset_faces = dlib.full_object_detections()
    apex_faces = dlib.full_object_detections()

    onset_faces.append(predictor(onset_image, onset_det))
    apex_faces.append(predictor(apex_image, apex_det))

    onset_crops = dlib.get_face_chips(onset_image, onset_faces, size=320)
    apex_crops = dlib.get_face_chips(apex_image, apex_faces, size=320)

    onset_crop = onset_crops[0][:280, 50:270]
    apex_crop = apex_crops[0][:280, 50:270]

    onset_cropped = Image.fromarray(cv2.cvtColor(onset_crop, cv2.COLOR_BGR2RGB))
    apex_cropped = Image.fromarray(cv2.cvtColor(apex_crop, cv2.COLOR_BGR2RGB))

    onset_g = cv2.cvtColor(onset_crops[0], cv2.COLOR_RGB2GRAY)
    apex_g = cv2.cvtColor(apex_crops[0], cv2.COLOR_RGB2GRAY)

    pic_size = onset_crops[0].shape
    hsv = np.zeros(pic_size)
    hsv[:,:,1] = cv2.cvtColor(apex_crops[0], cv2.COLOR_RGB2HSV)[:,:,1]

    flow = cv2.calcOpticalFlowFarneback(onset_g, apex_g, flow=None,
                                        pyr_scale=0.5, levels=1, winsize=15,
                                        iterations=2,
                                        poly_n=5, poly_sigma=1.1, flags=0)

    mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])

    hsv[:,:,0] = ang * (180/ np.pi / 2)
    hsv[:,:,2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)
    hsv = np.asarray(hsv, dtype=np.float32)
    rgb_flow = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
    rgb_flow = Image.fromarray(rgb_flow.astype('uint8'))

    rgb_flow.save(flow_save_path)
    onset_cropped.save(onset_save_path)
    apex_cropped.save(apex_save_path)
コード例 #2
0
ファイル: crop.py プロジェクト: mateusjunges/tcc
def main(args):

    print('Extracting faces...')
    t_inicio = time.time()

    images_folder = args.image_folder
    output_folder = args.output_folder

    size = 155
    padding = 0.1

    actor = 0

    predictor_path = "dlib/shape_predictor_5_face_landmarks.dat"
    # Load all the models we need: a detector to find the faces, a shape predictor
    # to find face landmarks so we can precisely localize the face
    dlib_frontal_face_detector_file = open(
        "dlib/dlib_frontal_face_detector.dat", "rb")
    detector = pickle.load(dlib_frontal_face_detector_file)
    #detector = dlib.get_frontal_face_detector()
    sp = dlib.shape_predictor(predictor_path)

    for folder in sorted(os.listdir(images_folder)):
        actor += 1
        done = 0
        n_images = len(next(os.walk(images_folder + '/' + folder))[2])
        if actor > 12:
            for path in sorted(os.listdir(images_folder + '/' + folder)):

                image_path = images_folder + '/' + folder + '/' + path
                imgname = os.path.splitext(path)[0]
                #print(image)
                img = dlib.load_rgb_image(image_path)
                # Ask the detector to find the bounding boxes of each face.
                dets = detector(img, 0)
                num_faces = len(dets)
                if (num_faces == 1):
                    faces = dlib.full_object_detections()
                    faces.append(sp(img, dets[0]))
                    aligned = dlib.get_face_chips(img, faces, size, padding)
                    #img_list.append(aligned[0])
                    save_path = output_folder + '/' + folder + '/' + "{}.png".format(
                        imgname)
                    directory = os.path.dirname(save_path)
                    if not os.path.exists(directory):
                        os.makedirs(directory)
                    #print(save_path)
                    final_image = cv2.cvtColor(aligned[0], cv2.COLOR_BGR2RGB)
                    cv2.imwrite(save_path, final_image,
                                [cv2.IMWRITE_JPEG_QUALITY, 100])
                    #misc.imsave(save_path, aligned[0])

                done = done + 1
                print("Processing Actor {}... {}/{} ({} %)".format(
                    actor, done, (n_images), round((done / (n_images)) * 100,
                                                   2)))

    t2 = time.time()
    print('Extracting faces complete!')
    print("Tempo total: {}".format(t2 - t_inicio))
コード例 #3
0
 def align(self, img):
     face_locations, bboxes = self.detect_faces(img)
     shape = self.predictor(img, face_locations[0])
     self.faces.append(shape)
     images = dlib.get_face_chips(img, self.faces, size=112)
     self.faces = dlib.full_object_detections()
     return Image.fromarray(images[0])
コード例 #4
0
 def alignment(self,
               image_list,
               shape_predictor_path=configs_shape_predictor_path):
     """人脸对齐函数"""
     detector = dlib.get_frontal_face_detector()
     shape_predictor = dlib.shape_predictor(self.shape_predictor_path)
     # 使用opencv加载图片
     for i in self.image_list:
         bgr_img = cv2.imread(i)
         if i is None:
             print("无法加载{}".format(i))
             continue
         img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2RGB)
         dets = detector(img, 1)
         num_faces = len(dets)
         if num_faces == 0:
             print('没有找到人脸, 文件路径{}'.format(i))
             continue
         # 找到5个特征点进行校准
         faces = dlib.full_object_detections()
         for d in dets:
             faces.append(shape_predictor(img, d))
         # 得到校准人脸图片并显示
         # images = dlib.get_face_chips(img, faces, size=160, padding=0.25)
         images = dlib.get_face_chips(img, faces, size=320)
         for img in images:
             show_cv_image(img)
コード例 #5
0
def get_descriptor(load_name):
    img_rd = cv2.imread(load_name)
    rgb_img = cv2.cvtColor(img_rd, cv2.COLOR_BGR2RGB)
    #img = skimage.io.imread(load_name)
    dets = detector(rgb_img, 1)
    # 识别人脸特征点,并保存下来
    faces = dlib.full_object_detections()
    for det in dets:
        faces.append(sp(rgb_img, det))

    images = dlib.get_face_chips(rgb_img, faces, size=500)
    # 显示计数,按照这个计数创建窗口
    image_cnt = 0
    # 显示对齐结果
    for image in images:
        image_cnt += 1
        cv_rgb_image = np.array(image).astype(np.uint8)  # 先转换为numpy数组
        cv_bgr_image = cv2.cvtColor(cv_rgb_image, cv2.COLOR_RGB2BGR)  # opencv下颜色空间为bgr,所以从rgb转换为bgr
    img = cv2.cvtColor(cv_rgb_image, cv2.COLOR_BGR2RGB)
    assert len(dets) == 1
    shape = sp(img, dets[0])
    face_descriptor = facerec.compute_face_descriptor(img, shape)
    face_descriptor = np.array(face_descriptor)
    assert face_descriptor.shape == (128,)
    return face_descriptor
コード例 #6
0
def test_face_alignment():
    """
    input: image including faces
    output:aligned faces

    You can get the shape_predictor_5_face_landmarks.dat from:
    http://dlib.net/files/shape_predictor_5_face_landmarks.dat.bz2
    :return:
    """
    img_path = 'data/running_man.jpg'
    img = cv2.imread(img_path)
    img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    hog_face_detector = dlib.get_frontal_face_detector()
    shape_predictor = dlib.shape_predictor('shape_predictor_5_face_landmarks.dat')

    rects, scores, idx = hog_face_detector.run(img_rgb, 2, 0)
    faces = dlib.full_object_detections()
    for rect in rects:
        faces.append(shape_predictor(img_rgb, rect))

    # get the aligned face images
    images = dlib.get_face_chips(img, faces, size=320)
    for ind, image in enumerate(images):
        print(ind)
        # image_patch = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
        cv2.imshow('patch{}'.format(ind), image)

    # get a single chip
    print('faces[0]', faces[0])
    image = dlib.get_face_chip(img, faces[0], size=80)
    cv2.imshow('single chip', image)

    cv2.waitKey(0)
    cv2.destroyAllWindows()
コード例 #7
0
    def make_align(self, img):
        img = img.convert("RGB")
        height, width = img.size
        if width <= height:
            new_width = 128
            new_height = new_width * height // width
        else:
            new_height = 128
            new_width = new_height * width // height
        img = img.resize((new_height, new_width))

        img_array = np.array(img)

        detections = [det.rect for det in self.detector(img_array, 1)]

        num_faces = len(detections)

        if num_faces != 0:
            face = dlib.full_object_detections()
            face.append(self.predictor(img_array, detections[0]))

            image = dlib.get_face_chips(img_array, face)
            output_image = Image.fromarray(image[0]).convert("RGB").resize(
                (128, 128))

            return output_image

        else:
            return None
コード例 #8
0
    def get_face_chips(self, image, dets, padding=0.25, size=320):

        print("\nAlligning face using dlib..")

        # If HOG based face detection
        if self.detector == self.hog_face_detector:

            for detection in dets:
                self.faces.append(self.sp(image, detection))

        # If CNN based face detection
        else:
            for detection in dets:
                self.faces.append(self.sp(image, detection.rect))

        # Get the alligned face images
        images = dlib.get_face_chips(image,
                                     self.faces,
                                     size=size,
                                     padding=padding)

        for image in images:
            cv2.imshow("asd", image)
            cv2.waitKey(0)
        print("Image successfully alligned and resized to size %s" % size)

        return images
コード例 #9
0
def regist_face(root_dir):
    fts = np.zeros((1, 256))
    labels = []
    for file in os.listdir(root_dir):
        img = cv2.imdecode(np.fromfile(root_dir + '/' + file, dtype=np.uint8),
                           -1)
        dets = detector(img, 1)
        num_faces = len(dets)
        if num_faces == 0:
            continue
        faces = dlib.full_object_detections()
        for det in dets:
            faces.append(sp(img, det))
        images = dlib.get_face_chips(img, faces, size=224)
        labelName = file.split('.')[0]
        image = images[0]
        X = np.empty((1, 3, imgsize, imgsize))
        # BGR
        averageImg = [131.0912, 103.8827, 91.4953]
        X[0, 0, :, :] = image[:, :, 0] - averageImg[0]
        X[0, 1, :, :] = image[:, :, 1] - averageImg[1]
        X[0, 2, :, :] = image[:, :, 2] - averageImg[2]
        out = net.forward_all(data=X)
        feature = np.float64(out['feat_extract'])
        feature = np.reshape(feature, (1, 256))
        fts = np.concatenate((fts, feature))
        labels.append(labelName)

        cv2.waitKey(2)

    cv2.destroyAllWindows()

    fts = fts[1:, :]

    return labels, fts
コード例 #10
0
def aligned_face_cropper(indexedFileNames, crpFileDir, imgRes, scope):
    # 'indexedFileNames'는 총 분량으로부터 할당받아 온 원본 파일들의 이름과, 그 할당분의 순번(index), 'crpFileDir'은 얼굴 부분만 자른 것을 저장할 경로.
    # 'imgRes'는 이미지를 저장할 해상도(다수 선택 가능)에 대한 Parameter, 'scope'는 이미지 내에서 인물 부분이 차지하는 범위를 설정하는 Parameter 값이다.
    from tqdm import tqdm
    import matplotlib.pyplot as plt
    import dlib
    import time

    cnt = 0  # 출력돼 나온 총 파일의 수를 계수할 변수를 0으로 초기화하며 선언한다.
    coreNum, fileNames = indexedFileNames
    # 'indexedFileNames'은 멀티프로세싱을 위해 총 작업량으로부터 분할받은 부분과 그 index 정보로,
    # index 부분을 'coreNum'으로, 할당받은 자료 부분을 'fileNames'로 각각 Un-packaging.
    # 'coreNum'이라고 해서 실제 CPU 내에서 해당 Core의 물리적인 할당 번호를 의미하는 것은 아니다!!
    # 중복의 방지와 진행률 표시 시의 구분을 위한 단순한 코드 상의 넘버링일 뿐이다.

    timeFlag = time.strftime('%m%d-%H%M%S', time.localtime(time.time()))   # 모듈 작동 당시의 시각을 기억해 둠.(파일명의 중복 방지에 활용하기 위함)
    shapePrd = dlib.shape_predictor('D:/HSH/Model/shape_predictor_68_face_landmarks.dat')   # 학습된 형태 예측기의 모델 파일을 불러옴.(!!!!! Github 용량 제한으로 포함돼있지 않음 !!!!!)
    faceDtcr = dlib.get_frontal_face_detector()   # 얼굴 정면을 탐지하는 dlib의 Method를 변수화.
    faceDirs = []   # 출력한 파일을 다른 함수 등에 활용할 수 있도록, 작업을 통해 출력된 파일의 이름들을 저장할 배열 선언.

    for fileName in tqdm(fileNames, desc="@Core {} - Aligning & Cropping".format(coreNum)):
        # 특정 폴더 내 사진들의 이름 리스트인 'fileNames'의 내용에 따라 이미지를 불러온 후, 컨테이너에 적재.
        if plt.imread(fileName).shape[0] < 600:
            continue   # 읽어 올 이미지의 크기가 정사각형 한 차원 기준 600픽셀 미만이라면, 작업을 진행하지 않고 다음 파일로 넘어가도록 처리하였다.
        imgLoaded = dlib.load_rgb_image(fileName)   # 파일을 RGB Color 이미지로 불러옴.
        dtcdFaces = faceDtcr(imgLoaded, 1)   # 불러온 이미지에서 얼굴(들)을 탐지해 변수에 저장.
        objects = dlib.full_object_detections()    # 탐지해 낸 랜드마크 포인트들을 담을 변수를 선언.

        for dtcdFace in dtcdFaces:  # 찾은 얼굴 부분 안에서 모델을 이용해 랜드마크 포인트들을 탐지.
            if dtcdFace.right() - dtcdFace.left() < 200:
                continue   # 탐지해 낸 얼굴 부분의 한 차원 기준 크기가 200픽셀 미만이면, 작업을 진행하지 않고 다음 파일로 넘어간다.

            shape = shapePrd(imgLoaded, dtcdFace)
            objects.append(shape)  # 찾아낸 랜드마크 포인트들의 정보를 앞서 선언해 둔 변수에 적재.

        for res in imgRes:
            # 이미지를 저장할 해상도를 복수 선택할 수 있게 해 뒀으므로, 그 선택지를 입력한 수 만큼 반복해 작동한다.
            saveCnt = 0   # 저장한 파일을 계수할 변수 선언.
            # 'cropFileDir'은 Crop해 온 파일들이 저장될 포괄적 폴더의 경로, 'res'는 그 폴더 안에 생성될 또 다른 폴더의 이름이자 저장될 해상도이다.
            dir = '{}{}/'.format(crpFileDir, str(res))
            try:
                # 탐지한 포인트 정보와 주어진 Parameter 값들을 가지고 얼굴을 바르게 정렬한 후 잘라낸 다음, 적재한다.
                # 개별 파일에 대한 작업 도중 오류가 발생할 시(얼굴을 탐지하지 못했다거나 등의 경우),
                # 그 오류로 인해 전체 과정이 중단돼버리는 대신, 오류를 무시하고 다음 파일로 그냥 넘어갈 수 있도록 Exception 처리를 하였다.
                # 즉, 특정 몇몇 파일로부터 얼굴을 찾지 못했더라도 이를 그냥 무시하고, 다른 파일에서라도 얼굴을 찾아냈다면 그 것들은 온전히 가져올 수 있도록 한 것이다.
                face = dlib.get_face_chips(imgLoaded, objects, size=res, padding=scope)
                # 앞서 추출해 낸 얼굴을 Parameter값(해상도, 인물 부분의 표현 범위)에 따라 .png 파일로 출력.
                # 동일 인물의 중복 출력을 방지하기 위해 한 사진 당 얼굴 하나씩만을 출력하도록 했다.
                fileDir = '{}{}_Aligned_{}_{}_{}_{}.png'.format(dir, int(scope), timeFlag, coreNum, res, cnt)  # 파일명을 형식에 따라 설정.
                dlib.save_image(face[0], fileDir)  # 'face'배열의 가장 첫 내용만을 지정한 파일명으로 저장.
                faceDirs.append(fileDir)  # 나중 과정에 활용할 수 있도록, 잘라내 저장한 얼굴들에 대한 파일명을 배열에 추가.
                saveCnt += 1  # 저장한 파일의 수를 1 증가시킨다.
            except Exception as e:
                break

        cnt += saveCnt
        # 'saveCnt'는 for Loop의 내부변수이기 때문에, 매 Iteration 시마다 초기화될 것이므로,
        # 회 당 산출된 값을 매 Iteration이 종료될 때마다 전역변수에 더해놓아 줘야 그 수가 의미를 상실하지 않는다.

    return faceDirs, cnt  # 출력한 파일들의 이름들 목록과 그 총 수를 호출측에 반환.
コード例 #11
0
ファイル: predict.py プロジェクト: pilotbear/FairFace
def detect_face(image_paths, SAVE_DETECTED_AT, size=300, padding=0.25):
    cnn_face_detector = dlib.cnn_face_detection_model_v1(
        'dlib_models/mmod_human_face_detector.dat')
    sp = dlib.shape_predictor(
        'dlib_models/shape_predictor_5_face_landmarks.dat')
    base = 2000  # largest width and height
    for index, image_path in enumerate(image_paths):
        if index % 1000 == 0:
            print('---%d/%d---' % (index, len(image_paths)))

        img = dlib.load_rgb_image(image_path)
        img = dlib.resize_image(img, 628, 628)
        dets = cnn_face_detector(img, 1)
        num_faces = len(dets)
        if num_faces == 0:
            print(
                "Sorry, there were no faces found in '{}'".format(image_path))
            continue
        # Find the 5 face landmarks we need to do the alignment.
        faces = dlib.full_object_detections()
        for detection in dets:
            rect = detection.rect
            faces.append(sp(img, rect))
        images = dlib.get_face_chips(img, faces, size=size, padding=padding)
        for idx, image in enumerate(images):
            img_name = image_path.split("/")[-1]
            path_sp = img_name.split(".")
            face_name = os.path.join(
                SAVE_DETECTED_AT,
                path_sp[0] + "_" + "face" + str(idx) + "." + path_sp[-1])
            dlib.save_image(image, face_name)
コード例 #12
0
    def _get_normal_image(self):
        """获取标准化后的人脸图片和人脸位置"""

        # 为了提高人脸检测速度,首先进行图片大小resize,最小边在缩放到100;
        if self.use_scaled:
            height, width, channel = self.image.shape
            scale = min(height, width) / 100
            scale_image = cv2.resize(self.image, (int(width / scale), int(height / scale)))

            scale_det_list = detector(scale_image, 1)

            det_list = [dlib.rectangle(
                left=int(scale_det.left() * scale),
                top=int(scale_det.top() * scale),
                right=int(scale_det.right() * scale),
                bottom=int(scale_det.bottom() * scale),
            ) for scale_det in scale_det_list]
        else:
            det_list = detector(self.image, 1)

        faces = dlib.full_object_detections()

        if len(det_list) == 0:
            return [], []

        for det in det_list:
            faces.append(shape_predictor(self.image, det))

        return dlib.get_face_chips(self.image, faces, size=150, padding=0.25), det_list
コード例 #13
0
def face_crop(path, files):
    global count
    predictor_model = '/Users/zcyyy/Documents/硕士学习/临时/dataset/AFEW/shape_predictor_68_face_landmarks.dat'
    detector = dlib.get_frontal_face_detector()  # dlib人脸检测器
    predictor = dlib.shape_predictor(predictor_model)
    pre_img = os.path.join(path, files)  # 读入时的图片绝对路径
    cur_img = str(count)+'.'+'jpg'
    cur_img = os.path.join(path, cur_img)  # 读出时的图片绝对路径
    print("file is {}".format(pre_img))
    # cv2读取图像
    img = cv2.imread(pre_img)
    # 人脸数rects
    rects = detector(img,0)
    # faces存储full_object_detection对象
    faces = dlib.full_object_detections()

    if len(rects) > 0:
        for i in range(len(rects)):
            faces.append(predictor(img, rects[i]))

        face_images = dlib.get_face_chips(
            img, faces, size=224)  # 输出尺寸(224,224)
        for image in face_images:
            cv2.imwrite(cur_img, image)
        count += 1
    else:
        print('未检测到人脸')
    os.system('rm {}'.format(pre_img))  # 去掉之前的图片
コード例 #14
0
def faceAlignment(img, detector, shapePredictor):
    # Find bounding boxes
    dets = detector(img, 0)

    num_faces = len(dets)
    if num_faces == 0:
        return [], []

    # Find face landmarks we need to do the alignment.
    faces = dlib.full_object_detections()
    frames = []
    for d in dets:
        faces.append(shapePredictor(img, d))
        frames.append([(d.left(), d.top()), (d.right(), d.bottom())])

    # Get the aligned face images
    # Optionally:
    # images = dlib.get_face_chips(img, faces, size=160, padding=0.25)
    imagesAligned = []
    images = dlib.get_face_chips(img, faces, size=320)
    for i, image in enumerate(images):
        #cv_bgr_img = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
        image = cv2.resize(image, (256, 256), interpolation=cv2.INTER_LINEAR)
        imagesAligned.append(image)

    # cv2.destroyAllWindows()

    return imagesAligned, frames
コード例 #15
0
def compare_face(root_dir, lbs, fts, result_dir):
    for file in os.listdir(root_dir):
        img = cv2.imdecode(np.fromfile(root_dir + '/' + file, dtype=np.uint8),
                           -1)
        dets = detector(img, 1)
        num_faces = len(dets)
        if num_faces == 0:
            print("Sorry, there were no faces found in current frame")
            continue
        top_allfaces = []
        bottom_allfaces = []
        right_allfaces = []
        left_allfaces = []
        for i in range(num_faces):
            face = [dets[i]]
            for k, d in enumerate(face):
                top_allfaces.append(d.top())
                bottom_allfaces.append(d.bottom())
                right_allfaces.append(d.right())
                left_allfaces.append(d.left())
        faces = dlib.full_object_detections()
        for det in dets:
            faces.append(sp(img, det))
        images = dlib.get_face_chips(img, faces, size=224)
        X = np.empty((num_faces, 3, imgsize, imgsize))
        # BGR
        averageImg = [131.0912, 103.8827, 91.4953]
        for i in range(len(images)):
            image = images[i]
            X[i, 0, :, :] = image[:, :, 0] - averageImg[0]
            X[i, 1, :, :] = image[:, :, 1] - averageImg[1]
            X[i, 2, :, :] = image[:, :, 2] - averageImg[2]
        out = net.forward_all(data=X)
        features = np.float64(out['feat_extract'])
        features = np.reshape(features, (num_faces, 256))
        all_scores = []
        compar_pic(features, fts, all_scores)
        for j in range(num_faces):
            scores = all_scores[0][j].tolist()
            bestscore = max(scores)
            bestscore_index = scores.index(bestscore)
            likelyuser = lbs[bestscore_index]
            if bestscore > thershold:
                cv2.putText(img, likelyuser,
                            (left_allfaces[j], top_allfaces[j] - 5),
                            cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
                cv2.rectangle(img, (left_allfaces[j], top_allfaces[j]),
                              (right_allfaces[j], bottom_allfaces[j]),
                              (0, 255, 0), 2)
            else:
                ROI_temp = img[top_allfaces[j]:bottom_allfaces[j],
                               left_allfaces[j]:right_allfaces[j], :]
                ROI = cv2.resize(ROI_temp, (imgsize, imgsize),
                                 interpolation=cv2.INTER_LINEAR)
                cv2.imwrite(result_dir + '/' + str(j) + '.jpg', ROI)

        cv2.imwrite(result_dir + '/' + 'result.jpg', img)

    cv2.destroyAllWindows()
コード例 #16
0
ファイル: saveFace.py プロジェクト: u19900101/ImgManage
def getdemo(face_file_path):
    # 导入人脸检测模型
    print("当前检测图片为:",face_file_path)
    predicter_path ='shape_predictor_68_face_landmarks.dat'
    detector = dlib.get_frontal_face_detector()
    # 导入检测人脸特征点的模型
    sp = dlib.shape_predictor(predicter_path)
    # 读入图片
    bgr_img=cv2.imdecode(np.fromfile(face_file_path,dtype=np.int8),-1)
    # bgr_img = cv2.imread(face_file_path)
    if bgr_img is None:
        print("Sorry, we could not load '{}' as an image".format(face_file_path))
        return
    # opencv的颜色空间是BGR,需要转为RGB才能用在dlib中
    rgb_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2RGB)
    # bgr_img = cv2.imread(face_file_path)
    if(rgb_img.shape[0]<2000):
        scale = 3000.0/rgb_img.shape[1]
        rgb_img = cv2.resize(rgb_img,(3000,int(rgb_img.shape[0]/(rgb_img.shape[1])*3000)))

    # opencv的颜色空间是BGR,需要转为RGB才能用在dlib中
    # rgb_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2RGB)
    # 检测图片中的人脸
    dets = detector(rgb_img, 1)
    # (top, right, bottom, left)  803  982  892  892
    # (left,top, right, bottom) 892  803  982  892
    # 检测到的人脸数量
    faceNum = len(dets)
    print(faceNum)
    if faceNum == 0:
        print("Sorry, there were no faces found in '{}'".format(face_file_path))
        return

    face_locations = []
    for det in dets:
        face_locations.append((det.top(),det.right(),det.bottom(),det.left()))

    faceDic = {}
    faceDic['faceNum'] = faceNum
    face_landmarks = face_recognition.face_landmarks(rgb_img,face_locations) #72个点
    face_encodings = face_recognition.face_encodings(rgb_img,face_locations)


    # 识别人脸特征点,并保存下来
    faces = dlib.full_object_detections()
    for det in dets:
        faces.append(sp(rgb_img, det))

    # 人脸对齐
    images = dlib.get_face_chips(rgb_img, faces, size=320)
    # 显示计数,按照这个计数创建窗口
    image_cnt = 0
    # 显示对齐结果
    for image in images:
        image_cnt += 1
        cv_rgb_image = np.array(image).astype(np.uint8)# 先转换为numpy数组
        cv_bgr_image = cv2.cvtColor(cv_rgb_image, cv2.COLOR_RGB2BGR)# opencv下颜色空间为bgr,所以从rgb转换为bgr
        print("正在保存图片 :" + str(image_cnt)+'.jpg')
        cv2.imwrite('./'+str(image_cnt)+'.jpg',cv_bgr_image)
コード例 #17
0
def align_faces(img):
    dets = detector(img, 1)
    objs = dlib.full_object_detections()
    for detection in dets:
        s = sp(img, detection)
        objs.append(s)
    faces = dlib.get_face_chips(img, objs, size=256, padding=0.35)  #얼굴 영역만 잘라줌
    return faces
コード例 #18
0
def align_faces(img):
    dets = detector(img, 1) # detector는 얼굴 찾아주는 변수 //dets는 얼굴들이 들어있음
    objs = dlib.full_object_detections()
    for detection in dets:
        s = sp(img, detection)
        objs.append(s)
    faces = dlib.get_face_chips(img, objs, size=256, padding=0.35) # get_face_chips는 얼굴 영역만 잘라서 이미지로 만들어 준다.
    return faces
コード例 #19
0
def align_faces(img):
    dets = detector(img, 1)  #dets에 얼굴 영역정보
    objs = dlib.full_object_detections()
    for detection in dets:  #얼굴들 중 얼굴 갯수만큼 .
        s = sp(img, detection)  #s : landmark (점에 대한 정보)
        objs.append(s)
    faces = dlib.get_face_chips(img, objs, size=256,
                                padding=0.35)  #얼굴 영역만 잘라 이미지를 만들어주는 것
    return faces
コード例 #20
0
def align_faces(img):
    dets = detector(img, 1)  #dets:얼굴 영역정보들이 들어있음.(폭, 높이, 위치 등)
    objs = dlib.full_object_detections()  #객체를 찾아
    for detection in dets:
        s = sp(img, detection)  #점에 대한 정보
        objs.append(s)
        faces = dlib.get_face_chips(img, objs, size=256,
                                    padding=0.35)  #faces: 얼굴 이미지들이 들어있음.
        return faces
コード例 #21
0
def align_faces(img):
    dets = detector(img)  #얼굴 찾기 dets: 얼굴들이 들어가있음
    objs = dlib.full_object_detections()  #objs는 비어있음. 포인트 찾아주는 object 객체
    for detection in dets:  #얼굴들 이미지 갯수만큼 for문 돔
        s = sp(img, detection)  # s: landmark 다섯개 점에 대한 정보
        objs.append(s)  #objs에 점 5개 저장
    faces = dlib.get_face_chips(img, objs, size=256,
                                padding=0.35)  #faces 자른 얼굴 영역저장 --> 얼굴 이미지로 저장
    return faces  #얼굴 이미지들
コード例 #22
0
def align_faces(img):  # 얼굴 이미지들을 return 해주는 함수
    dets = detector(img, 1)  # 이미지 속 얼굴 정보 저장되어 있는 곳
    objs = dlib.full_object_detections()  # object에 대한 정보가 들어있는 객체 (위치 정보)
    for detection in dets:  # dets - 얼굴 영역 정보
        s = sp(img, detection)  # s = landmark 정보를 갖고있음
        objs.append(s)
    faces = dlib.get_face_chips(
        img, objs, size=256, padding=0.35)  # 이미지에서 얼굴 영역만 추출해주는 것  / 얼굴 이미지들
    return faces
コード例 #23
0
ファイル: ex02_makeup_GAN.py プロジェクト: gunusong/GAN
def align_faces(img):
    dets = detector(img, 1) # 1채널

    objs = dlib.full_object_detections()

    for detection in dets:
        s = predictor(img, detection)
        objs.append(s)
    faces = dlib.get_face_chips(img, objs, size=256, padding=1)
    return faces
コード例 #24
0
def align_faces(img):
    dets = detector(img, 1)  #얼굴을 찾음
    objs = dlib.full_object_detections()  #객체를 찾아줌 (사람/고양이 등등)
    for detection in dets:
        s = sp(img, detection)
        objs.append(s)
    faces = dlib.get_face_chips(
        img, objs, size=256,
        padding=0.35)  #padding왜 0.35? ->얼굴 det된것에서 +0.35 더 보려고
    return faces
コード例 #25
0
def face_crop():
    for i in range(len(rects)):
        faces.append(predictor(img, rects[i]))
        # print(rects[i])

    face_images = dlib.get_face_chips(img, faces, size=320)
    for image in face_images:
        cv_bgr_img = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
        # cv2.imwrite('../output/Messi_clip.png', cv_bgr_img)
    return cv_bgr_img
コード例 #26
0
def align_faces(img):
    dets = detector(img, 1)  #여기에서 이미지의 얼굴을 찾아서 img에서 넣어주었다.
    objs = dlib.full_object_detections()  #사진의 위치정보를 찾는 코드(여기에서는 사진속에 얼굴의 위치정보)

    for detection in dets:
        s = sp(img, detection)  #이미지에서 landmark(점)를 가져온다
        objs.append(s)  #가져온 landmark를 얼굴의 위치정보에 붙여준다.
    faces = dlib.get_face_chips(img, objs, size=256,
                                padding=0.35)  #이미지에서 얼굴 잘라서 보여주는 코드
    return faces
コード例 #27
0
def align_faces(img):  # 함수
    dets = detector(img, 1)  # 얼굴 찾기
    objs = dlib.full_object_detections()
    for detection in dets:
        s = sp(img, detection)  # s= landmark(점 5개)
        objs.append(s)
    faces = dlib.get_face_chips(
        img, objs, size=256, padding=0.35
    )  # get_face_chips -> 얼굴영역만 잘라서 이미지로 만듦 / padding - 얼굴영역 상하좌우로 0.35만큼 더 출력
    return faces
コード例 #28
0
ファイル: data.py プロジェクト: sja9527/face-retrieval
 def alignment(self, img):
     img_cv = cv2.cvtColor(np.asarray(img),cv2.COLOR_RGB2BGR)
     dets = self.align_detect(img_cv, 1)
     if len(dets)!=0:
         faces = dlib.full_object_detections()
         for det in dets:
             faces.append(self.sp(img_cv, det))
         face_img = dlib.get_face_chips(img_cv, faces, size=160)
         return Image.fromarray(cv2.cvtColor(face_img[0],cv2.COLOR_BGR2RGB))
     else:
         return Image.fromarray(cv2.cvtColor(img_cv,cv2.COLOR_BGR2RGB))
コード例 #29
0
def align_faces(img):
    dets = detector(img, 1)  # 얼굴 찾기, dets는 얼굴에 대한 영역(범위 및 좌표)관련 정보를 가지고 있다.
    objs = dlib.full_object_detections(
    )  # 이미지를 구분하기 위해 이미지에 대한 정보를 갖고 있는 객체. 그러나 처음에는 공란이다.
    for detection in dets:
        s = sp(img, detection)  # 얼굴에 있는 랜드마크(점) 정보를 나타낸다.
        objs.append(s)  # 얼굴마다 랜드마크를 붙여 objs에 저장된다.
    faces = dlib.get_face_chips(
        img, objs, size=256, padding=0.35)  # 랜드마크된 얼굴 범위를 추출해서 얼굴 이미지로 나타낸다.
    # padding은 추출한 얼굴 사진에 상하좌우 여분을 추가해서 추출한다. => 얼굴 외에 얼굴 근처 사진도 같이 추출되는 효과
    return faces
コード例 #30
0
def extract_face_and_get_embedding(img, required_size):
       
        dets = detector(img, 3)
        num_faces = len(dets)

        if num_faces == 0:

            rects = face_cascade.detectMultiScale(img, minNeighbors = 5)
            if len(rects) != 0:
                
                for x, y, w, h in rects:
                   
                    roi_face = img[y-5:y+h+10, x-5:x+w+10]
                    image = np.array(roi_face)
                    image = cv2.resize(image, (required_size, required_size), interpolation = cv2.INTER_AREA)
                    face_pixels = image.astype('float32')
                    mean, std = face_pixels.mean(), face_pixels.std()
                    face_pixels = (face_pixels - mean) / std
                    samples = np.expand_dims(face_pixels, axis=0)

                    yhat = model.predict(samples)
                    return yhat[0]
                    
            elif len(rects) == 0:
                print('Sorry, there were no faces found in the image')
                
            else:
                print('More than one number of faces found in the image')

        elif num_faces == 1:

            faces = dlib.full_object_detections()
            
            for detection in dets:
                faces.append(predictor(img, detection))

            image = dlib.get_face_chips(img, faces, size = required_size, padding = 0.2)

            image = np.array(image)
            
            image = image.reshape(required_size, required_size, 3)
            face_pixels = image.astype('float32')

            mean, std = face_pixels.mean(), face_pixels.std()
            face_pixels = (face_pixels - mean) / std
            samples = np.expand_dims(face_pixels, axis=0)
            print('Computation going on.....')
            yhat = model.predict(samples)

            return yhat[0]
        
        else:
            
            print('More than one number of faces found in the image')
コード例 #31
0
ファイル: test_numpy_returns.py プロジェクト: 20337112/dlib
def get_test_face_chips():
    rgb_img, shape = get_test_image_and_shape()
    shapes = dlib.full_object_detections()
    shapes.append(shape)
    return dlib.get_face_chips(rgb_img, shapes)
コード例 #32
0
# Ask the detector to find the bounding boxes of each face. The 1 in the
# second argument indicates that we should upsample the image 1 time. This
# will make everything bigger and allow us to detect more faces.
dets = detector(img, 1)

num_faces = len(dets)
if num_faces == 0:
    print("Sorry, there were no faces found in '{}'".format(face_file_path))
    exit()

# Find the 5 face landmarks we need to do the alignment.
faces = dlib.full_object_detections()
for detection in dets:
    faces.append(sp(img, detection))

window = dlib.image_window()

# Get the aligned face images
# Optionally: 
# images = dlib.get_face_chips(img, faces, size=160, padding=0.25)
images = dlib.get_face_chips(img, faces, size=320)
for image in images:
    window.set_image(image)
    dlib.hit_enter_to_continue()

# It is also possible to get a single chip
image = dlib.get_face_chip(img, faces[0])
window.set_image(image)
dlib.hit_enter_to_continue()