예제 #1
0
    def generate(names, targets):
        ret, frame = vid_source.read()
        # tensor code
        while ret:
            img_bg = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            image = Image.fromarray(img_bg)
            try:
                bboxes, faces = face_recognize.align_multi(image)
            except:
                bboxes = []
                faces = []
            if len(bboxes) != 0:
                bboxes = bboxes[:,:-1] #shape:[10,4],only keep 10 highest possibiity faces
                bboxes = bboxes.astype(int)
                bboxes = bboxes + [-1,-1,1,1] # personal choice   
                results, score, embs = face_recognize.infer(faces, targets)

                for idx, bbox in enumerate(bboxes):
                    if False:
                        frame = draw_box_name(bbox, names[results[idx] + 1] + '_{:.2f}'.format(score[idx]), frame)
                    else:
                        frame = draw_box_name(bbox, names[results[idx] + 1], frame)

            payload = cv2.imencode('.jpg', frame)[1].tobytes()
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + payload + b'\r\n')
            ret, frame = vid_source.read()
예제 #2
0
def recognize_webcam(image_np):
    # image = cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB)
    image = Image.fromarray(image_np)
    # try:
    bboxes, faces = face_recognize.align_multi(image)
    # except:
    #     # pass
    #     bboxes = []
    #     faces = []

    if len(bboxes) != 0:
        bboxes = bboxes[:,:-1] #shape:[10,4],only keep 10 highest possibiity faces
        bboxes = bboxes.astype(int)
        bboxes = bboxes + [-1,-1,1,1] # personal choice   
        
        results, score, embs = face_recognize.infer(faces, targets)
        for idx, bbox in enumerate(bboxes):
            
            is_spoofing = face_recognize.is_spoofing(faces[idx])
            status = "attack"
            if not is_spoofing:
                status = "genuine"
            if len(que_name) > 15:
                que_name.pop()
                que_name.append(names[results[idx] + 1]+ '_{:.7s}'.format(status))
            else:
                que_name.append(names[results[idx] + 1]+ '_{:.7s}'.format(status))
            if False:
                image_np = draw_box_name(bbox, names[results[idx] + 1] + '_{:.2f}__{:.7s}'.format(score[idx], status), image_np)
            else:
                image_np = draw_box_name(bbox, names[results[idx] +1 ], image_np)
    return image_np
예제 #3
0
def process_two_image(data):
    folder_name = str(uuid.uuid1())
    command = 'mkdir %s' % folder_name
    subprocess.call(command, shell=True)
    image_path_origin = download_file_by_url(data['image_url_origin'],
                                             folder_name)
    image_path_detection = download_file_by_url(data['image_url_detection'],
                                                folder_name)

    from api import face_recognize
    conf = get_config()
    face_recognize = face_recognize(conf)
    face_recognize._raw_load_single_face(image_path_origin)
    targets = face_recognize.embeddings
    image = Image.open(image_path_detection)
    submiter = [['image_url', 'x1', 'y1', 'x2', 'y2', 'result']]
    try:
        bboxes, faces = face_recognize.align_multi(image)
    except:
        bboxes = []
        faces = []
    if len(bboxes) > 0:
        bboxes = bboxes[:, :-1]
        bboxes = bboxes.astype(int)
        bboxes = bboxes + [-1, -1, 1, 1]
        results, score = face_recognize.infer(faces, targets)

        for id, (re, sc) in enumerate(zip(results, score)):
            if re != -1:
                temp = {
                    'x1': bboxes[id][0],
                    'y1': bboxes[id][1],
                    'x2': bboxes[id][2],
                    'y2': bboxes[id][3],
                    'result': 1
                }
                temp = [
                    data['image_url_detection'], bboxes[id][0], bboxes[id][1],
                    bboxes[id][2], bboxes[id][3], 1
                ]
                submiter.append(temp)
    command = 'rm -rf %s' % folder_name
    subprocess.call(command, shell=True)
    df = pd.DataFrame.from_records(submiter)
    headers = df.iloc[0]
    df = pd.DataFrame(df.values[1:], columns=headers)
    df = df.sort_values(by=['result'], ascending=False)
    results = df.to_json(orient='records')
    return results
예제 #4
0
def process_images(image_path='', path=''):
    from api import face_recognize
    conf = get_config()
    face_recognize = face_recognize(conf)
    face_recognize._raw_load_single_face(image_path)
    targets = face_recognize.embeddings
    submiter = [['image', 'x1', 'y1', 'x2', 'y2', 'result']]
    list_file = glob.glob(path + '/*')
    if os.path.isfile(list_file[0]) == False:
        path = list_file[0]
        print(path)
    for img in tqdm(glob.glob(path + '/*')):
        temp = [img.split('/')[-1], 0, 0, 0, 0, 0]
        image = Image.open(img)
        try:
            bboxes, faces = face_recognize.align_multi(image)
        except:
            bboxes = []
            faces = []
        if len(bboxes) > 0:
            bboxes = bboxes[:, :-1]
            bboxes = bboxes.astype(int)
            bboxes = bboxes + [-1, -1, 1, 1]
            results, score = face_recognize.infer(faces, targets)

            for id, (re, sc) in enumerate(zip(results, score)):
                if re != -1:
                    temp = [
                        img.split('/')[-1], bboxes[id][0], bboxes[id][1],
                        bboxes[id][2], bboxes[id][3], 1
                    ]
        submiter.append(temp)
    df = pd.DataFrame.from_records(submiter)
    headers = df.iloc[0]
    df = pd.DataFrame(df.values[1:], columns=headers)
    df = df.sort_values(by=['result'], ascending=False)
    results = df.to_json(orient='records')
    return results
예제 #5
0
def recognize(image_path, targets, names):
    frame = cv2.imread(image_path)
    image = Image.fromarray(frame).convert('RGB')
    try:
        bboxes, faces = face_recognize.align_multi(image)
    except:
        bboxes = []
        faces = []
    result = {}
    result['original'] = encode_image(image.copy())

    if len(bboxes) != 0:
        bboxes = bboxes[:,:-1] #shape:[10,4],only keep 10 highest possibiity faces
        bboxes = bboxes.astype(int)
        bboxes = bboxes + [-1,-1,1,1] # personal choice   
        results, score, embs = face_recognize.infer(faces, targets)
        
        for idx, bbox in enumerate(bboxes):
            result[names[results[idx] + 1]] = encode_image(faces[idx])
            if False:
                frame = draw_box_name(bbox, names[results[idx]+1] + '_{:.2f}'.format(score[idx]), frame)
            else:
                frame = draw_box_name(bbox, names[results[idx]+1], frame)
    return result
예제 #6
0
        isSuccess, frame = cap.read()
        if isSuccess:         
            img_bg = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            image = Image.fromarray(img_bg)
            try:
                bboxes, faces = face_recognize.align_multi(image, thresholds = [0.5, 0.7, 0.8])
                j+=1
            except:
                bboxes = []
                faces = []

            if len(bboxes) != 0:
                bboxes = bboxes[:,:-1] #shape:[10,4],only keep 10 highest possibiity faces
                bboxes = bboxes.astype(int)
                bboxes = bboxes + [-1,-1,1,1] # personal choice   
                results, score, embs = face_recognize.infer(faces, targets)

                for idx, bbox in enumerate(bboxes):
                    if results[idx] == -1 and args.save_unknow:
                        new_per = "%s/unknow_%s"%(conf.facebank_path, count_unknow)
                        if not os.path.exists(new_per):
                            os.mkdir(new_per)
                        
                        faces[idx].save('%s/%s.jpg'%(new_per, datetime.now().date().strftime('%Y%m%d')))
                        targets = torch.cat((targets, embs[idx].unsqueeze(0)), dim=0)
                        names =np.append(names, 'unknow_%s'%count_unknow)
                        count_unknow+=1

                    if args.score:
                        frame = draw_box_name(bbox, names[results[idx]] + '_{:.2f}'.format(score[idx]), frame)
                    else: