Example #1
0
def create_face(images_dir, out_face_dir):
    '''
    生成人脸数据图库,保存在out_face_dir中,这些数据库将用于生成embedding数据库
    :param images_dir:
    :param out_face_dir:
    :return:
    '''
    # image_list=file_processing.get_files_list(images_dir, postfix='jpg')
    image_list, names_list = file_processing.gen_files_labels(images_dir,
                                                              postfix='jpg')
    face_detect = face_recognition.Facedetection()
    for image_path, name in zip(image_list, names_list):
        image = image_processing.read_image(image_path,
                                            resize_height=0,
                                            resize_width=0,
                                            normalization=False)
        # 获取 判断标识 bounding_box crop_image
        bounding_box, points = face_detect.detect_face(image)
        bounding_box = bounding_box[:, 0:4].astype(int)
        bounding_box = bounding_box[0, :]
        print("face box:{}".format(bounding_box))
        face_image = image_processing.crop_image(image, bounding_box)
        # image_processing.show_image("face", face_image)
        # image_processing.show_image_box("face",image,bounding_box)
        out_path = os.path.join(out_face_dir, name)
        face_image = image_processing.resize_image(face_image, resize_height,
                                                   resize_width)
        if not os.path.exists(out_path):
            os.mkdir(out_path)
        basename = os.path.basename(image_path)
        out_path = os.path.join(out_path, basename)
        image_processing.save_image(out_path, face_image)
Example #2
0
def create_face_embedding(model_path,dataset_path,out_emb_path,out_filename):
    # 建立npy文件
    files_list,names_list=file_processing.gen_files_labels(dataset_path,postfix=['*.jpg'])
    embeddings,label_list=get_face_embedding(model_path,files_list, names_list)
    print("label_list:{}".format(label_list))
    print("have {} label".format(len(label_list)))
    embeddings=np.asarray(embeddings)
    np.save(out_emb_path, embeddings)
    file_processing.write_list_data(out_filename, label_list, mode='w')
Example #3
0
def create_embedding(model_path, emb_face_dir):
    face_net = face_recognition.facenetEmbedding(model_path)
    image_list, names_list = file_processing.gen_files_labels(emb_face_dir,
                                                              postfix='jpg')
    images = image_processing.get_images(image_list, 160, 160, whiten=True)
    compare_emb = face_net.get_embedding(images)
    h5file = h5py.File('face.h5', 'w')
    h5file['X_train'] = compare_emb
    h5file.close()
    file_processing.write_data('name.txt', image_list, model='w')
def create_face(images_dir, out_face_dir):
    print(images_dir)
    '''
    生成人脸数据图库,保存在out_face_dir中,这些数据库将用于生成embedding数据库
    :param images_dir:
    :param out_face_dir:
    :return:
    '''
    # image_list=file_processing.get_files_list(images_dir, postfix='jpg')
    image_list, names_list = file_processing.gen_files_labels(images_dir)
    face_detect = face_recognition.Facedetection()
    for image_path, name in zip(image_list, names_list):
        print("图片的路径", str(image_path))
        if image_path == 'dataset/images/.DS_Store':
            continue
        if image_path == 'dataset/images/face1/.DS_Store':
            continue
        if image_path == 'dataset/images/face2/.DS_Store':
            continue
        if image_path == 'dataset/images/face3/.DS_Store':
            continue
        if image_path == 'dataset/images/face4/.DS_Store':
            continue
        if image_path == './dataset/emb_face/.DS_Store':
            continue
        image = image_processing.read_image(image_path,
                                            resize_height=0,
                                            resize_width=0,
                                            normalization=False)
        # 获取 判断标识 bounding_box crop_image
        bounding_box, points = face_detect.detect_face(image)
        bounding_box = bounding_box[:, 0:4].astype(int)
        if (len(bounding_box) < 1):
            continue
        bounding_box = bounding_box[0, :]
        print("face box:{}".format(bounding_box))
        face_image = image_processing.crop_image(image, bounding_box)
        # image_processing.show_image("face", face_image)
        # image_processing.show_image_box("face",image,bounding_box)
        out_path = os.path.join(out_face_dir, name)
        if (len(face_image) > 0):
            face_image = image_processing.resize_image(face_image,
                                                       resize_height,
                                                       resize_width)
        else:
            continue
        if not os.path.exists(out_path):
            os.mkdir(out_path)
        basename = os.path.basename(image_path)
        out_path = os.path.join(out_path, basename)
        image_processing.save_image(out_path, face_image)
Example #5
0
def create_face(images_dir, out_face_dir):
    '''
    生成人脸数据图库,保存在out_face_dir中,这些数据库将用于生成embedding数据库
    '''
    #此处引用自定义函数 : file_processing.gen_files_labels(images_dir,postfix='jpg')
    #返回值:   图像数组:  images_dir下所有文件(是的,你没想错!包括子目录下的所有文件)的路径(Path)会被存储到image_list
    #         标签数组:  names_list就是相应的的"文件名或子目录名",在本项目中,子目录名 将作为 作为样本的标签(即ID,e.g.姓名 或 学号之类的)

    print('#2nd--Mtcnn人脸库')

    image_list,names_list=file_processing.gen_files_labels(images_dir,postfix='jpg')
    
    face_detect=face_recognition.Facedetection()
    
    for image_path ,name in zip(image_list,names_list):
        
        # try:
        image=image_processing.read_image(image_path, resize_height=0, resize_width=0, normalization=False)
        
        # 获取 判断标识 bounding_box crop_image
        bounding_box, points = face_detect.detect_face(image)
        bounding_box = bounding_box[:,0:4].astype(int)
        
        # try:
        bounding_box=bounding_box[0,:]
        # except:
        # print("跳过当前图片")
            # continue
        
        print("矩形框坐标为:{}".format(bounding_box))
        
        face_image = image_processing.crop_image(image,bounding_box)
        # except:
            # print("当前图像帧格式非法,将被忽略")
        
        out_path=os.path.join(out_face_dir,name)
        
        face_image=image_processing.resize_image(face_image, resize_height, resize_width)
        
        if not os.path.exists(out_path):
            os.mkdir(out_path)
        
        basename=os.path.basename(image_path)

        out_path=os.path.join(out_path,basename)

        image_processing.save_image(out_path,face_image)
Example #6
0
def main():
    conn = pymysql.connect(host="localhost",
                           port=3306,
                           user="******",
                           password="******",
                           db="test")
    cursor = conn.cursor()

    # 1.激活
    ret = fun.Activate(Appkey, SDKey)
    if ret == 0 or ret == 90114:
        print('激活成功:', ret)
    else:
        print('激活失败:', ret)
        pass

    # 2.初始化
    ret = fun.initAll()
    if ret[0] == 0:
        print('初始化成功:', ret, '句柄', fun.Handle)
    else:
        print('初始化失败:', ret)
        pass

    files_list, names_list = file_processing.gen_files_labels(
        asf_dataset_path, postfix=['*.jpg'])
    asf_embeddings, asf_label_list = fun.Feature_extract_batch(
        fun, files_list, names_list)  # 特征,标签
    print("label_list:{}".format(asf_label_list))
    print("have {} label".format(len(asf_label_list)))
    for f, name in zip(asf_embeddings, asf_label_list):
        # print(f.feature, f.featureSize)

        f_bytes = BytesIO(string_at(f.feature, f.featureSize))
        # print("f.getvalue():", len(f.getvalue()), f.getvalue())
        # a.write(f.getvalue())
        sql = '''
                insert into asf_user_face_info(name, feature_size, feature, create_time)
                values ("%s", %d, "%s", "%s")
            ''' % (str(name), f.featureSize,
                   str(base64.b64encode(f_bytes.getvalue())), str(time.time()))

        # print(sql)
        cursor.execute(sql)
    cursor.execute("commit")
    cursor.close()
Example #7
0
def create_embedding(model_path, emb_face_dir, out_emb_path, out_filename):
    '''
    产生embedding数据库,这些embedding其实就是人脸特征
    '''
    print('#3rd--FaceNet人脸库')

    face_net = face_recognition.facenetEmbedding(model_path)

    image_list,names_list=file_processing.gen_files_labels(emb_face_dir,postfix='jpg')
    
    images= image_processing.get_images(image_list,resize_height,resize_width,whiten=True)
    
    compare_emb = face_net.get_embedding(images)
    
    np.save(out_emb_path, compare_emb)


    file_processing.write_data(out_filename, names_list, model='w')
Example #8
0
def create_face_embedding(model_path, dataset_path, out_emb_path,
                          out_filename):
    '''

    :param model_path: faceNet模型路径
    :param dataset_path: 人脸数据库路径,每一类单独一个文件夹
    :param out_emb_path: 输出embeddings的路径
    :param out_filename: 输出与embeddings一一对应的标签
    :return: None
    '''
    files_list, names_list = file_processing.gen_files_labels(
        dataset_path, postfix=['*.jpg', '*jpeg'])
    embeddings, label_list = get_face_embedding(model_path, files_list,
                                                names_list)
    print("label_list:{}".format(label_list))
    print("have {} label".format(len(label_list)))

    embeddings = np.asarray(embeddings)
    np.save(out_emb_path, embeddings)
    file_processing.write_list_data(out_filename, label_list, mode='w')
Example #9
0
def create_embedding(model_path, emb_face_dir, out_emb_path, out_filename):
    '''
    产生embedding数据库,保存在out_data_path中,这些embedding其实就是人脸的特征
    :param model_path:
    :param emb_face_dir:
    :param out_emb_path:
    :param out_filename:
    :return:
    '''
    face_net = face_recognition.facenetEmbedding(model_path)
    # image_list=file_processing.get_files_list(emb_face_dir,postfix='jpg')
    image_list, names_list = file_processing.gen_files_labels(emb_face_dir,
                                                              postfix='jpg')
    images = image_processing.get_images(image_list,
                                         resize_height,
                                         resize_width,
                                         whiten=True)
    compare_emb = face_net.get_embedding(images)
    np.save(out_emb_path, compare_emb)

    # 可以选择保存image_list或者names_list作为人脸的标签
    # 测试时建议保存image_list,这样方便知道被检测人脸与哪一张图片相似
    file_processing.write_data(out_filename, image_list, model='w')
def face_recognition_for_bzl(model_path, test_dataset, filename):
    # 加载数据库的数据
    dataset_emb, names_list = predict.load_dataset(dataset_path, filename)
    print("loadind dataset...\n names_list:{}".format(names_list))
    # 初始化mtcnn人脸检测
    face_detect = face_recognition.Facedetection()
    # 初始化facenet
    face_net = face_recognition.facenetEmbedding(model_path)

    #获得测试图片的路径和label
    filePath_list, label_list = file_processing.gen_files_labels(test_dataset)
    label_list = [name.split('_')[0] for name in label_list]
    print("filePath_list:{},label_list{}".format(len(filePath_list),
                                                 len(label_list)))

    right_num = 0
    wrong_num = 0
    detection_num = 0
    test_num = len(filePath_list)
    for image_path, label_name in zip(filePath_list, label_list):
        print("image_path:{}".format(image_path))
        # 读取图片
        image = image_processing.read_image_gbk(image_path)
        # 人脸检测
        bboxes, landmarks = face_detect.detect_face(image)
        bboxes, landmarks = face_detect.get_square_bboxes(bboxes,
                                                          landmarks,
                                                          fixed="height")
        if bboxes == [] or landmarks == []:
            print("-----no face")
            continue
        if len(bboxes) >= 2 or len(landmarks) >= 2:
            print("-----image have {} faces".format(len(bboxes)))
            continue
        # 获得人脸框区域
        face_images = image_processing.get_bboxes_image(
            image, bboxes, resize_height, resize_width)
        face_images = image_processing.get_prewhiten_images(face_images,
                                                            normalization=True)
        # face_images = image_processing.get_prewhiten_images(face_images,normalization=True)

        pred_emb = face_net.get_embedding(face_images)
        pred_name, pred_score = predict.compare_embadding(pred_emb,
                                                          dataset_emb,
                                                          names_list,
                                                          threshold=1.3)
        # 在图像上绘制人脸边框和识别的结果
        # show_info = [n + ':' + str(s)[:5] for n, s in zip(pred_name, pred_score)]
        # image_processing.show_image_text("face_recognition", image, bboxes, show_info)

        index = 0
        pred_name = pred_name[index]
        pred_score = pred_score[index]
        if pred_name == label_name:
            right_num += 1
        else:
            wrong_num += 1
        detection_num += 1
        print(
            "-------------label_name:{},pred_name:{},score:{:3.4f},status:{}".
            format(label_name, pred_name, pred_score,
                   (label_name == pred_name)))
    # 准确率
    accuracy = right_num / detection_num
    # 漏检率
    misdetection = (test_num - detection_num) / test_num
    print("-------------right_num/detection_num:{}/{},accuracy rate:{}".format(
        right_num, detection_num, accuracy))
    print(
        "-------------misdetection/all_num:{}/{},misdetection rate:{}".format(
            (test_num - detection_num), test_num, misdetection))
Example #11
0
    SDKey = b'D5QB8ARVCxWsTLAeWi2SqAmXkVToqWCVAto6UNce3mXd'
    ret = fun.Activate(Appkey, SDKey)  # 激活
    if ret == 0 or ret == 90114:
        log.logger.info("激活成功: %s" % (ret))
    else:
        log.logger.warn("激活失败: %s" % (ret))
        pass

    ret = fun.initAll()  # 初始化
    if ret[0] == 0:
        log.logger.info("初始化成功: %s, 句柄: %s" % (ret, fun.Handle))
    else:
        log.logger.warn("初始化失败: %s" % (ret))

    # 3.拿到files_list和names_list
    files_list, names_list = file_processing.gen_files_labels(
        data_path, postfix=['*.jpg'])

    # 4.数据预处理,过滤掉有多个人的图片,确保每个人只有一张图片
    start = time.time()
    emb_file_list = []
    emb_name_list = []
    already_existing_list = []  # 已经存在于nameList的人,不用再往特征集准备数据里放
    for file, name in zip(files_list, names_list):
        if name not in already_existing_list:  # 如果该人照片没有被处理过,则进行人脸检测,过滤掉图中多个人脸的
            frame = cv2.imdecode(np.fromfile(file, dtype=np.uint8),
                                 cv2.IMREAD_COLOR)
            bboxes, landmarks = face_detect.detect_face(frame)
            if len(bboxes) == 1:  # 只有一个人
                emb_file_list.append(file)  # 文件列表
                emb_name_list.append(name)  # 标签列表
                already_existing_list.append(name)  # 该人已被处理
Example #12
0
def face_recognition_for_bzl(model_path,dataset_path,test_dataset, filename,threshold):
    # 获得测试图片的路径和label
    filePath_list, label_list=file_processing.gen_files_labels(test_dataset,postfix=None)
    label_list=[name.split('_')[0] for name in label_list]
    print("filePath_list:{},label_list{}".format(len(filePath_list),len(label_list)))
    face_face_recognition_batch(model_path,dataset_path,filename,filePath_list,label_list,threshold)