Team Ai
Apppublic

ryderprogram/FaceRecognition

sourceHugging Facegpl-3.0updated 4y agoView on Hugging Face
0likes
app.py189 linesDownload Raw Back to root
1# Face Recognition Hub2# author: Zeng Yifu(曾逸夫)3# creation time: 2022-07-284# email: zyfiy1314@163.com5# project homepage: https://gitee.com/CV_Lab/face-recognition-hub6 7import os8import sys9from pathlib import Path10 11import face_recognition12import gradio as gr13from PIL import Image, ImageDraw, ImageFont14 15from util.fonts_opt import is_fonts16 17ROOT_PATH = sys.path[0]  # 项目根目录18 19IMG_PATH_Test = "./img_examples/unknown"20 21FONTSIZE = 1522 23OCR_TR_DESCRIPTION = '''# Face Recognition24<div id="content_align">https://github.com/ageitgey/face_recognition demo</div>'''25 26def str_intercept(img_path):27    img_path_ = img_path[::-1]28    point_index = 0  # 记录反转后第一个点的位置29    slash_index = 0  # 记录反转后第一个斜杠的位置30 31    flag_pi = 032    flag_si = 033 34    for i in range(len(img_path_)):35        if (img_path_[i] == "." and flag_pi == 0):36            point_index = i37            flag_pi = 138 39        if (img_path_[i] == "/" and flag_si == 0):40            slash_index = i41            flag_si = 142 43    point_index = len(img_path) - 1 - point_index44    slash_index = len(img_path) - 1 - slash_index45 46    return point_index, slash_index47 48 49# 人脸录入50def face_entry(img_path, name_text):51    if img_path == "" or name_text == "" or img_path is None or name_text is None:52        return None, None, None53 54    point_index, slash_index = str_intercept(img_path)55    img_renamePath = f"{img_path[:slash_index+1]}{name_text}{img_path[point_index:]}"56    os.rename(img_path, img_renamePath)57    img_ = Image.open(img_renamePath)58    print(img_renamePath)59 60    return img_, img_renamePath, name_text61 62 63# 设置示例64def set_example_image(example: list):65    return gr.Image.update(value=example[0])66 67 68def face_recognition_(img_srcPath, img_tagPath, img_personName):69    if img_tagPath == "" or img_tagPath is None:70        return None71 72    image_of_person = face_recognition.load_image_file(img_srcPath)73    person_face_encoding = face_recognition.face_encodings(image_of_person)[0]74 75    known_face_encodings = [76        person_face_encoding,]77 78    known_face_names = [79        img_personName,]80 81    test_image = face_recognition.load_image_file(img_tagPath)82 83    face_locations = face_recognition.face_locations(test_image)84    face_encodings = face_recognition.face_encodings(test_image, face_locations)85 86    pil_image = Image.fromarray(test_image)87    img_pil = ImageDraw.Draw(pil_image)88    textFont = ImageFont.truetype(str(f"{ROOT_PATH}/fonts/SimSun.ttf"), size=FONTSIZE)89    #     ymin, xmax, ymax, xmin90    for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):91        matches = face_recognition.compare_faces(known_face_encodings, face_encoding)92 93        name = "Unknown Person"94 95        if True in matches:96            first_matches_index = matches.index(True)97            name = known_face_names[first_matches_index]98 99        img_pil.rectangle([left, top, right, bottom], fill=None, outline=(255, 228, 181), width=2)  # 边界框100        text_w, text_h = textFont.getsize(name)  # 标签尺寸101        # 标签背景102        img_pil.rectangle(103            (left, top, left + text_w, top + text_h),104            fill=(255, 255, 255),105            outline=(255, 255, 255),106        )107 108        # 标签109        img_pil.multiline_text(110            (left, top),111            name,112            fill=(0, 0, 0),113            font=textFont,114            align="center",115        )116 117    del img_pil118    return pil_image119 120 121def main():122    is_fonts(f"{ROOT_PATH}/fonts")  # 检查字体文件123 124    with gr.Blocks(css='style.css') as demo:125        gr.Markdown(OCR_TR_DESCRIPTION)126 127        # -------------- 人脸识别 录入 --------------128        with gr.Row():129            gr.Markdown("### Step 01: Face Entry")130        with gr.Row():131            with gr.Column():132                with gr.Row():133                    input_img = gr.Image(image_mode="RGB", source="upload", type="filepath", label="face entry")134                with gr.Row():135                    input_name = gr.Textbox(label="Name")136                with gr.Row():137                    btn = gr.Button(value="Entry")138 139            with gr.Column():140                with gr.Row():141                    output_ = gr.Image(image_mode="RGB", source="upload", type="pil", label="entry image")142                    input_srcImg = gr.Variable(value="")143                    input_srcName = gr.Variable(value="")144        with gr.Row():145            example_list = [["./img_examples/known/ChengLong.jpg", "成龙"],146                            ["./img_examples/known/VinDiesel.jpg", "VinDiesel"],147                            ["./img_examples/known/JasonStatham.jpg", "JasonStatham"],148                            ["./img_examples/known/ZhenZidan.jpg", "甄子丹"]]149            gr.Examples(example_list,150                        [input_img, input_name],151                        output_,152                        set_example_image,153                        cache_examples=False)154 155 156        # -------------- 人脸识别 测试 --------------157        with gr.Row():158                gr.Markdown("### Step 02: Face Test")159        with gr.Row():160            with gr.Column():161                with gr.Row():162                    input_img_test = gr.Image(image_mode="RGB", source="upload", type="filepath", label="test image")163                with gr.Row():164                    btn_test = gr.Button(value="Test")165                with gr.Row():166                    paths = sorted(Path(IMG_PATH_Test).rglob('*.jpg'))167                    example_images_test = gr.Dataset(components=[input_img],168                                                     samples=[[path.as_posix()] for path in paths])169 170            with gr.Column():171                with gr.Row():172                    output_test = gr.Image(image_mode="RGB", source="upload", type="pil", label="identify image")173 174        btn.click(fn=face_entry, inputs=[input_img, input_name], outputs=[output_, input_srcImg, input_srcName])175 176        btn_test.click(fn=face_recognition_,177                       inputs=[input_srcImg, input_img_test, input_srcName],178                       outputs=[output_test])179        example_images_test.click(fn=set_example_image, inputs=[180            example_images_test,], outputs=[181                input_img_test,])182 183        return demo184 185 186if __name__ == "__main__":187    demo = main()188    demo.launch(inbrowser=True)189