Beispiel #1
0
def threshold2(img_dir):
    t1 = time.time()
    mtcnn = load_mtcnn()
    t2 = time.time()
    print('mtcnn loaded, time: %.2f' % (t2 - t1))

    imgs = load_imgs(mtcnn, img_dir, False)
    t1 = time.time()
    print('images loaded, count: %d, time: %.2f' % (len(imgs), t1 - t2))

    with tf.Graph().as_default():
        with tf.Session() as sess:
            t1 = time.time()
            model = load_pretrain_model()
            t2 = time.time()
            print('pretrained model loaded, time: %.2f' % (t2 - t1))
            embeddings = calc_embeddings(model, sess, imgs)
            diff = np.subtract(embeddings[0::2], embeddings[1::2])
            dist = np.sum(np.square(diff), 1)
            print('dist same person', dist)

            em1 = [embeddings[0], embeddings[1]]
            em2 = [embeddings[2], embeddings[3]]
            diff = np.subtract(em1, em2)
            dist = np.sum(np.square(diff), 1)
            print('dist diff person', dist)
Beispiel #2
0
def threshold(img_dir):
    t1 = time.time()
    mtcnn = load_mtcnn()
    t2 = time.time()
    print('mtcnn loaded, time: %.2f' % (t2 - t1))

    imgs = load_imgs(mtcnn, img_dir)
    random.shuffle(imgs)
    t1 = time.time()
    print('images loaded, count: %d, time: %.2f' % (len(imgs), t1 - t2))

    batch_count = 10
    batch_size = math.floor(len(imgs) / 10)

    thresholds = np.arange(0.3, 1.2, 0.01)
    threshold_accuracies = []
    with tf.Graph().as_default():
        with tf.Session() as sess:
            t1 = time.time()
            model = load_pretrain_model()
            t2 = time.time()
            print('pretrained model loaded, time: %.2f' % (t2 - t1))
            embeddings = calc_embeddings(model, sess, imgs)
            for i in range(batch_count - 1):
                t1 = time.time()
                ta = find_best_threshold(
                    imgs[batch_size * i:batch_size * (i + 1)],
                    embeddings[batch_size * i:batch_size * (i + 1)],
                    thresholds)
                t2 = time.time()
                threshold_accuracies.append(ta)
                print('batch: %d, threshold %f, accuracy: %f, time: %.2f' %
                      (i, ta[0], ta[1], t2 - t1))

            ta = np.mean(threshold_accuracies, 0)
            threshold = ta[0]
            accuracy = ta[1]
            print('mean threshold: %f, mean accuracy: %f' %
                  (threshold, accuracy))

            #test
            accuracy = calc_accuracy(imgs[batch_size * 9:],
                                     embeddings[batch_size * 9:], threshold)

            print('test accuracy: ', accuracy)
Beispiel #3
0
def to_lfw(src_dir, dst_dir):
    if (not os.path.isdir(dst_dir)):
        os.makedirs(dst_dir)

    mtcnn = load_mtcnn()
    dirs = os.listdir(src_dir)
    for person in dirs:
        person_dir = os.path.join(src_dir, person)
        if (not os.path.isdir(person_dir)):
            continue
        dst_person_dir = os.path.join(dst_dir, person)
        if (not os.path.isdir(dst_person_dir)):
            os.mkdir(dst_person_dir)

        files = os.listdir(person_dir)
        for file in files:
            img_file = os.path.join(person_dir, file)
            detect_align(mtcnn, img_file, dst_person_dir)
Beispiel #4
0
def main():
    REDIS_EXPIRE = 10

    mtcnn = load_mtcnn()

    r = redis.Redis('localhost', 6379, password='******')

    while (True):
        print('wait to detect face!')
        filename = r.brpop('face_detect')
        filename = bytes.decode(filename[1])
        # print('filename', filename)

        imgpath = os.path.join('../uploads', filename)
        # print('imgpath', imgpath)

        start = time.time()
        faces = detect(mtcnn, imgpath, '../uploads/detect')
        print('detect result: ', faces)
        count = faces['count']
        if count < 0:
            ret = {'status': -4, 'msg': 'detect face error'}
        else:
            ret = {
                'status': 0,
                'msg': 'success',
                'faces': count,
                'time': time.time() - start,
                'detectUrl': '/detect/' + filename,
                'rects': []
            }
            if (count > 0):
                ret['size'] = faces['size']
                for _, v in enumerate(faces['rects']):
                    ret['rects'].append({
                        'left': int(v[0]),
                        'top': int(v[1]),
                        'right': int(v[2]),
                        'bottom': int(v[3])
                    })
        r.expire(filename, REDIS_EXPIRE)
        print(ret)
        r.lpush(filename, json.dumps(ret))
Beispiel #5
0

def calc_embeddings(model, sess, imgs, image_size=160):
    images_placeholder = model[0]
    embeddings = model[1]
    phase_train_placeholder = model[2]
    nrof_images = len(imgs)
    images = np.zeros((nrof_images, image_size, image_size, 3))
    for i in range(nrof_images):
        images[i, :, :, :] = imgs[i]
    feed_dict = {images_placeholder: images, phase_train_placeholder: False}
    emb_array = sess.run(embeddings, feed_dict=feed_dict)
    return emb_array


def calc_distance(embeddings1, embeddings2):
    diff = np.subtract(embeddings1, embeddings2)
    return np.sum(np.square(diff), 1)


if __name__ == '__main__':
    mtcnn = load_mtcnn()
    img1 = load_img(mtcnn, '../face_test_img/bbh/1.jpg')
    img2 = load_img(mtcnn, '../face_test_img/bbh/2.jpg')

    with tf.Graph().as_default():
        with tf.Session() as sess:
            model = load_pretrain_model()
            embeddings = calc_embeddings(model, sess, [img1, img2])
            dist = calc_distance([embeddings[0]], [embeddings[1]])
            print('distance', dist[0])
Beispiel #6
0
def main():
    REDIS_EXPIRE = 10

    mtcnn = load_mtcnn()
    with tf.Graph().as_default():
        with tf.Session() as sess:
            model = load_pretrain_model()

            r = redis.Redis('localhost', 6379, password='******')

            while (True):
                print('wait to compare face!')
                filename = r.brpop('face_compare')
                orig_filename = bytes.decode(filename[1])
                print('origfilename', orig_filename)
                filename = orig_filename.split('#')

                filename1 = filename[0]
                filename2 = filename[1]
                threshold = float(filename[2])

                # print('split', filename, filename1, filename2)

                imgpath1 = os.path.join('../uploads', filename1)
                imgpath2 = os.path.join('../uploads', filename2)
                # print('imgpath', imgpath1, imgpath2)

                start = time.time()
                rect1 = {'left': 0, 'top': 0, 'right': 0, 'bottom': 0}
                size1 = {'width': 0, 'height': 0}
                img1 = detect_align(mtcnn, imgpath1, '../uploads/align', False,
                                    160, True, rect1, size1)
                rect2 = {'left': 0, 'top': 0, 'right': 0, 'bottom': 0}
                size2 = {'width': 0, 'height': 0}
                img2 = detect_align(mtcnn, imgpath2, '../uploads/align', False,
                                    160, True, rect2, size2)
                if (img1 is None or img2 is None):
                    ret = {'status': -4, 'msg': 'detect face error'}
                else:
                    embeddings = calc_embeddings(model, sess, [img1, img2])
                    dist = calc_distance([embeddings[0]], [embeddings[1]])[0]
                    judge_time = time.time() - start
                    # print('judge time: ', judge_time)
                    if (dist <= threshold):
                        msg = "同一人可能性高"
                    # elif dist <= 1.1:
                    #     msg = "同一人可能性一般"
                    # elif dist <= 1.23:
                    #     msg = "不同人可能性一般"
                    else:
                        msg = "不同人可能性高"
                    ret = {
                        'status': 0,
                        'msg': msg,
                        'distance': dist.item(),
                        'time': judge_time,
                        'size1': size1,
                        'rect1': rect1,
                        'size2': size2,
                        'rect2': rect2
                    }

                r.expire(orig_filename, REDIS_EXPIRE)
                print(ret)
                r.lpush(orig_filename, json.dumps(ret))