InsightFace | 基于 AI 增强的人脸检测

点击下方卡片,关注“小白玩转Python”公众号

517bec47f6487b5d74d6b5565e2cec89.png

概述

我将使用InsightFace,这是一个以其在复杂面部分析任务中的卓越表现而闻名的开源AI工具包。该工具包可以帮助完成诸如人脸检测、关键点识别、情感识别、年龄和性别估算以及属性分析等任务。

示例

!pip install tqdm 
!pip install numpy
!pip install insightface 
!pip install opencv-python 
!pip install onnxruntime
!pip install pandas

存储 embeddings

#@title Iterate and create embeddings
#@markdown iterate through the directory and foldername will be name of the person
#@markdown create a directory called pics and add files there
import os
from tqdm import tqdm
from glob import glob
import numpy as np
import cv2 as cv2
import insightface
from insightface.app import FaceAnalysis
from insightface.data  import get_image as ins_get_image
app = FaceAnalysis(name='buffalo_l')
app.prepare(ctx_id=0, det_size=(640, 640))
names = []
embeddings =  []
folders = os.listdir(f'sample_data/pics')
for folder in tqdm(folders):
  if ".ipynb_checkpoints" in folder: continue
  print(folder)
  img_paths = glob(f'sample_data/pics/{folder}/*')
  for img_path in img_paths:
       img = cv2.imread(img_path)
       if img is None: continue
       faces = app.get(img)
       if len(faces) != 1: continue
       face = faces[0]
       names.append(folder)
       embeddings.append(face.normed_embedding)
embeddings = np.stack(embeddings, axis=0)

这段代码遍历包含以个人命名的文件夹的目录,每个文件夹代表一个人。假设目录结构包括一个存储个人图像文件的‘pics’子目录。使用InsightFace库,它初始化一个名为‘buffalo_l’的人脸分析应用程序,准备进行检测,并定义列表以存储姓名和人脸embeddings。代码然后遍历每个文件夹,从‘pics’子目录读取图像,并使用InsightFace进行人脸分析。如果成功检测到一张人脸且仅有一张人脸,个人的名字(文件夹名)将被添加到‘names’列表中,相应的人脸embeddings被附加到‘embeddings’列表中。最后,将人脸embeddings堆叠成一个NumPy数组。此代码本质上处理一组图像,使用InsightFace提取人脸embeddings,并将其与相应的个人关联,以便于人脸识别或分析任务。我为我的朋友和自己创建了embeddings,以便稍后可以使用该工具识别他们。

你可以使用这个数据集来尝试识别宝莱坞(印度电影业)名人。或者从HuggingFace获取这个数据集。数据集链接:https://huggingface.co/datasets/amitpuri/bollywood-celebs

识别人脸
#@title Match Face to the embeddings
#@markdown this code will match the existing embeddings and provide a score
import cv2
import numpy as np
from insightface.app import FaceAnalysis
def recognize_face(input_img, known_embeddings, app):
    # Perform face analysis on the input image
    faces = app.get(input_img)
    # Check if exactly one face is detected
    if len(faces) != 1:
        return "No face or multiple faces detected"
    # Retrieve the embedding for the detected face
    detected_embedding = faces[0].normed_embedding
    # Calculate similarity scores with known embeddings
    scores = np.dot(detected_embedding, np.array(known_embeddings).T)
    scores = np.clip(scores, 0., 1.)
    # Find the index with the highest score
    idx = np.argmax(scores)
    max_score = scores[idx]
    # Check if the maximum score is above a certain threshold (adjust as needed)
    threshold = 0.7
    if max_score >= threshold:
        recognized_name = names[idx]
        return f"Face recognized as {recognized_name} with a confidence score of {max_score:.2f}"
    else:
        return "Face not recognized"
# Assuming 'input_img_path' is the path to the input face image
input_img = cv2.imread("sample_data/pics/vishal/vishal.jpg")
# Call the recognize_face function
result = recognize_face(input_img, embeddings, app)
print(result)

这个函数recognize_face接受一个输入图像、一组已知人脸embeddings(known_embeddings)和一个InsightFace应用实例(app)。它利用InsightFace的人脸分析功能检测输入图像中的人脸。如果检测到恰好一张人脸,它会检索该人脸的归一化embeddings。随后,计算检测到的人脸embeddings已知embeddings之间的相似度分数,并应用阈值来确定匹配是否足够可信。如果最大相似度分数超过指定阈值,它会返回一个带有识别名称和置信度分数的识别消息。否则,它会指示该人脸未被识别。此函数设计用于人脸识别任务,通过比较embeddings来识别给定图像中的已知人脸。可以根据所需的置信水平调整阈值。

我用几张我的照片创建了embeddings,并能够匹配我的新照片。

检测人物

有时,检测照片中是否有实际人物存在是有用的。接下来的两段代码旨在实现这一点。

def detect_person(img, detector):
    bboxes, kpss = detector.detect(img)
    bboxes = np.round(bboxes[:,:4]).astype(np.int)
    kpss = np.round(kpss).astype(np.int)
    kpss[:,:,0] = np.clip(kpss[:,:,0], 0, img.shape[1])
    kpss[:,:,1] = np.clip(kpss[:,:,1], 0, img.shape[0])
    vbboxes = bboxes.copy()
    vbboxes[:,0] = kpss[:, 0, 0]
    vbboxes[:,1] = kpss[:, 0, 1]
    vbboxes[:,2] = kpss[:, 4, 0]
    vbboxes[:,3] = kpss[:, 4, 1]
    return bboxes, vbboxes
#@title Detect if there is person in the image
    import glob
    import matplotlib.pyplot as plt
    detector = insightface.model_zoo.get_model('scrfd_person_2.5g.onnx', download=True)
    detector.prepare(0, nms_thresh=0.5, input_size=(640, 640))
    img_paths = glob.glob('sample_data/pics/vishal/*.jpg')
    for img_path in img_paths:
        img = cv2.imread(img_path)
        bboxes, vbboxes = detect_person(img, detector)
        for i in range(bboxes.shape[0]):
            bbox = bboxes[i]
            vbbox = vbboxes[i]
            x1,y1,x2,y2 = bbox
            vx1,vy1,vx2,vy2 = vbbox
            cv2.rectangle(img, (x1,y1)  , (x2,y2) , (0,255,0) , 1)
            alpha = 0.8
            color = (255, 0, 0)
            for c in range(3):
                img[vy1:vy2,vx1:vx2,c] = img[vy1:vy2, vx1:vx2, c]*alpha + color[c]*(1.0-alpha)
            cv2.circle(img, (vx1,vy1) , 1, color , 2)
            cv2.circle(img, (vx1,vy2) , 1, color , 2)
            cv2.circle(img, (vx2,vy1) , 1, color , 2)
            cv2.circle(img, (vx2,vy2) , 1, color , 2)
        filename = img_path.split('/')[-1]
        plt.imshow(img)
        img

它首先导入必要的库并获取一个人物检测模型(scrfd_person_2.5g.onnx)实例。然后,代码准备检测器,指定GPU设备(0)、非最大抑制阈值(0.5)和输入图像大小(640x640)。使用glob获取图像路径,对于每张图像,代码调用detect_person函数以获取边界框(bboxes)和可见边界框(vbboxes)。然后,通过在检测到的人物周围绘制矩形并添加颜色突出显示来在图像上可视化边界框。最后,使用Matplotlib显示修改后的图像。此代码对于快速评估一组图像中是否存在人物以及可视化检测结果非常有用。

结果如下,它能够识别出照片中有一个人。

409ee78792f4b76eb672bc8e2d79aa86.png

你可以在此处尝试现场演示。链接:

https://huggingface.co/spaces/hysts/insightface-person-detection

#@title annotate multiple faces
#@markdown upload a file named firends.jpg in the folder sample_data/images/
import cv2
import numpy as np
from insightface.app import FaceAnalysis
from google.colab.patches import cv2_imshow
def annotate_faces(input_img, app):
    # Perform face analysis on the input image
    faces = app.get(input_img)
# Draw rectangles around detected faces
    annotated_img = input_img.copy()
    for face in faces:
        bbox = face.bbox.astype(int)
        cv2.rectangle(annotated_img, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2)
    # Display or save the annotated image
    cv2_imshow(annotated_img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
# Assuming 'input_img_path' is the path to the input image
input_img = cv2.imread("sample_data/images/friends.jpg")
# Call the annotate_faces function
annotate_faces(input_img, app)

annotate_faces函数接受一个输入图像和一个InsightFace应用实例(app)。它对输入图像进行人脸分析,使用app.get方法检测人脸,然后使用OpenCV在每个检测到的人脸周围绘制矩形。使用cv2_imshow函数显示带注释的图像。在这个特定示例中,假设有一个名为‘friends.jpg’的图像文件位于‘sample_data/images/’文件夹中。可以相应地调整实际的图像路径。此代码提供了指定图像中检测到的人脸的可视化表示。

396f5ddad265f5edf9d6990bea119d61.png

db6d22f74ffc6e1a369827309ad3c89b.png

最后的代码创建了一个单行的子图,列数等于检测到的人脸数量(len(faces))。对于每张人脸,它提取边界框坐标(bbox)并将其转换为整数。然后使用Matplotlib将每张人脸显示为一个单独的子图,其中面部区域是根据边界框坐标从原始图像(img)中提取的。::1用于在图像索引中反转颜色通道的顺序,从BGR到RGB。子图水平排列,每个子图关闭坐标轴以获得更清晰的可视化。此代码使用Matplotlib提供了指定图像中每个检测到的人脸的可视化表示。

a6e7eff1d2886e78cb8eb5b75a6d0c56.png

·  END  ·

HAPPY LIFE

e003d542955cbf0d84ff92f2506ef42a.png

本文仅供学习交流使用,如有侵权请联系作者删除

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/670496.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

yolov10/v8 loss详解

v10出了就想看看它的loss设计有什么不同,看下来由于v8和v10的loss部分基本一致就放一起了。 v10的论文笔记,还没看的可以看看,初步尝试耗时确实有提升 好记性不如烂笔头,还是得记录一下,以免忘了,废话结束…

tcp链接中的三次挥手是什么原因

一、tcp链接中的正常四次挥手过程? 刚开始双方都处于 ESTABLISHED 状态,假如是客户端先发起关闭请求。四次挥手的过程如下: 1、客户端打算关闭连接,此时会发送一个 TCP 首部 FIN 标志位被置为 1 的报文,也即 FIN 报文…

Pycharm的基础设置+Pycharm与AutoDL服务器连接

一.pycharm的基础设置 1.下载pycharm profession版,配置之前博客里面的解释器mask2 2.run detect.py 3.终端的设置 (1)先直接在终端里面pip install 我们再创建一个测试python文件:terninal_test.py 虽然上面安装成功了包&#x…

Nested KVM Hypervisor Support

Description Nested KVM是指基于虚拟化技术的虚拟机管理系统。 Nested KVM在Intel处理器上,KVM使用Intel的vmx(virtualmachine eXtensions)来提高虚拟机性能,即硬件辅助虚拟化技术。如果一台虚拟机能够和物理机一样支持vmx&…

秘塔AI搜索,看看如今的AI搜索能有多懂你

你们正在用的浏览器是哪一款? 平时搜索时是否也有过这样的经历,在搜索引擎里输入关键词,然后在一堆广告中大海捞针,一不小心就入了一刀999的坑,又或是陈年资料令人发懵,压根儿就别想找到宝藏资源&#xff…

【Qt秘籍】[007]-LineEdit Pushbutton控件

Qt的中有着各种各样的控件,相较于传统C/C的输出默认只能在控制台实现,Qt中可以有不同的接口实现各种不同的功能,下面我们将实现不同功能的输出 hello world! 标签Label 【Qt秘籍】[006]-Label实现Hello World程序-编程第一步-CSD…

Prime1 - 提权的另一种解法,彻底搞懂OpenSSL解密渗透提权,超强思路版。

提权枚举 现在我们直接从低权限用户开始;我们先按照提权步骤,简单的系统枚举 虽然我们知道可以利用系统版本低进行内核提权,内核提权虽然比较快比较方便,但也比较暴力,缺点非常明显;很容易导致系统服务中…

GIS结合物联网:塑造智慧地球的新篇章

在信息技术飞速发展的今天,地理信息系统(GIS)与物联网(IoT)的深度融合,正以前所未有的方式重塑着我们对世界的认知。本文将深入探讨GIS与物联网结合的原理、应用实践以及面临的挑战与未来展望,共…

刷代码随想录有感(88):贪心算法——加油站

题干&#xff1a; 代码&#xff1a; class Solution { public:int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {int totalcost 0;for(int i 0; i < gas.size(); i){totalcost gas[i] - cost[i];}if(totalcost < 0)return -1;int …

数据库、数据表的基本操作

1.数据库的基本操作 &#xff08;1&#xff09;创建数据库 &#xff08;2&#xff09;删除数据库 &#xff08;3&#xff09;将数据库的字符集修改为gbk gbk是汉字内码扩展规范&#xff0c;是GB2312和GB13000的扩展&#xff0c;主要用于简体中文。 &#xff08;4&#xff09;…

vmware 正版免费下载

Broadcom 已经收购了 vmware 并且对普通用户提供免费服务. 那么我们怎么去获取这个玩意呢, 注册完之后打开就是这么个狗屎 , 根本不知道在哪里下载&#xff0c;注册的时候还不能用国内邮箱更是超级狗屎 转到 dashboard 搜索 workstation Pro你会搜索到这么一个奇怪的网址然后…

LeetCode 算法:盛最多水的容器c++

原题链接&#x1f517;&#xff1a;盛最多水的容器 难度&#xff1a;中等⭐️⭐️ 题目 给定一个长度为 n 的整数数组 height 。有 n 条垂线&#xff0c;第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。 找出其中的两条线&#xff0c;使得它们与 x 轴共同构成的容器可以…

JavaSE——集合框架二(6/6)-(案例)补充知识:集合的嵌套(需求与分析、问题解决、运行测试)

目录 案例引入 需求与分析 问题解决 运行测试 集合的嵌套 顾名思义&#xff0c;指的是集合中的元素又是一个集合。 本篇通过一个案例对这一知识进行了解&#xff1a; 案例引入 需求与分析 要求在程序中记住如下省份和其对应的城市信息&#xff0c;记录成功后&#xff0…

【AI】llama-fs的 安装与运行

pip install -r .\requirements.txt Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved.Install the latest PowerShell for new features and improvements! https://aka.ms/PSWindows(venv) PS D:\XTRANS\pythonProject>

【错误记录】HarmonyOS 运行报错 ( Failure[MSG_ERR_INSTALL_FAILED_VERIFY_APP_PKCS7_FAIL] )

文章目录 一、报错信息二、问题分析二、解决方案 一、报错信息 在 DevEco Studio 中 , 运行程序 , 编译时正常编译 , 但是在真机运行时 , 报如下错误 , 核心报错信息是 " Failure[MSG_ERR_INSTALL_FAILED_VERIFY_APP_PKCS7_FAIL] " ; 完整报错信息 : 05/29 10:58:55…

【软件全套资料】软件项目各阶段各类资料文档支撑,项目申报,立项,开发,运维,交付,售后,体系认证,评审资质

在软件开发过程中&#xff0c;文档扮演着至关重要的角色。它不仅记录了项目的需求、设计和开发过程&#xff0c;还为项目的维护和管理提供了便利。本文将详细介绍软件开发文档的重要性和作用&#xff0c;以及需求分析、软件设计、开发过程、运维管理和项目管理等方面的文档编写…

大数据治理平台建设解决方案(66页PPT)

方案介绍&#xff1a; 本解决方案旨在构建一个集数据集成、数据存储、数据处理、数据分析和数据安全于一体的大数据治理平台&#xff0c;帮助企业实现数据资产的统一管理和高效利用&#xff0c;提升业务决策效率和准确性。本大数据治理平台建设解决方案旨在为企业提供全面、高…

支持AMD GPU的llm.c

anthonix/llm.c: LLM training in simple, raw C/HIP for AMD GPUs (github.com) llm.c for AMD devices This is a fork of Andrej Karpathys llm.c with support for AMD devices. 性能 在单个7900 XTX显卡上使用默认设置&#xff0c;目前的训练步骤耗时约为79毫秒&#x…

使用IDEA在WSL2的Ubuntu的docker中运行项目

1、新建项目 1.1 从远程仓库拉取代码 2、配置环境 2.1 配置IDEA运行环境 2.1.1 配置JDK 注意&#xff1a;Ubuntu 20.04运行项目请使用JDK11&#xff0c;使用JDK8会编译报错&#xff0c;报错如下&#xff1a; 2.1.2 配置Maven 2.1.3 配置运行环境 2.1.4 配置远程Debug 2.2、配…

“两客一危”车辆综合监控信息化产品及应用分析

引言 随着科技的不断进步和社会的发展&#xff0c;“两客一危”车辆&#xff08;即长途客车、旅游包车和危险品运输车&#xff09;的安全监管问题日益凸显。为了提升车辆的安全性能和管理效率&#xff0c;综合监控信息化产品应运而生。本文将对这一产品进行详细介绍&#xff0…