You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实时人脸识别程序:检测到指定人员时展示对应图片的实现求助

我来帮你搞定这个需求!核心思路是在识别到目标人员时,用单独的线程来展示图片(避免阻塞实时人脸识别的主循环),同时记录上一次展示的人员,防止短时间内重复弹窗。下面是具体的实现步骤和修改后的代码:

步骤1:准备依赖和图片映射
  • 先确保你安装了用于展示图片的库,推荐用Pillow或者OpenCV,这里先以Pillow为例:
    pip install pillow
    
  • 创建一个字典,把需要触发弹窗的人员和他们的图片路径对应起来,方便快速查找:
    # 自定义目标人员与图片的映射
    target_people_images = {
        "Alex": "alex_profile.jpg",
        # 可以继续添加更多人员,比如 "Emma": "emma_photo.png"
    }
    
步骤2:编写图片展示函数与状态跟踪

我们需要一个函数负责打开图片并在指定秒数后关闭,同时用变量记录上一次展示的人员,避免重复触发弹窗:

from PIL import Image
import threading
import time

# 记录上一次展示的人员,初始化为None
last_shown_person = None

def show_person_image(image_path, duration=3):
    """展示指定图片,duration秒后自动关闭"""
    try:
        img = Image.open(image_path)
        img.show(title="Target Person")
        # 等待指定时长后关闭图片(部分系统可能需要手动关闭,可根据实际情况调整)
        time.sleep(duration)
        img.close()
    except Exception as e:
        print(f"展示图片时出错: {str(e)}")

如果你觉得Pillow的窗口行为不够稳定,可以换成OpenCV实现,兼容性更好:

import cv2

def show_person_image(image_path, duration=3):
    img = cv2.imread(image_path)
    cv2.imshow("Target Person", img)
    # 等待duration秒(单位毫秒),或按下任意键提前关闭
    cv2.waitKey(duration * 1000)
    cv2.destroyWindow("Target Person")
步骤3:修改你的人脸识别循环逻辑

在你得到识别结果name之后,加入判断逻辑,触发图片展示:

import numpy as np
import face_recognition

# 假设你已经初始化了已知人脸编码和对应姓名列表
known_face_encodings = [...]  # 你的已知人脸编码集合
known_person = [...]  # 对应姓名列表
target_people_images = {"Alex": "alex_profile.jpg"}
last_shown_person = None

# 你的实时人脸识别主循环(比如处理摄像头帧的循环)
while True:
    # 这里是你获取视频帧、检测人脸编码的代码,示例:
    # frame = ...  # 从摄像头/视频流读取帧
    # face_locations = face_recognition.face_locations(frame)
    # face_encodings = face_recognition.face_encodings(frame, face_locations)
    
    face_names = []
    for face_encoding in face_encodings:
        # 你的原有匹配逻辑
        face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
        matches = list(face_distances <= 0.4)
        name = "Unknown"
        if True in matches:
            match_index = np.argmin(face_distances)
            name = known_person[match_index]
        face_names.append(name)
        
        # 新增:判断是否是目标人员,且不是上一次展示的人
        if name in target_people_images and name != last_shown_person:
            last_shown_person = name
            # 启动线程展示图片,避免阻塞主循环导致人脸识别卡顿
            threading.Thread(
                target=show_person_image,
                args=(target_people_images[name], 3)
            ).start()
    
    # 后续的人脸标注、帧显示等代码...
关键注意点
  • 线程处理:用线程来执行图片展示是为了不阻塞实时人脸识别的主循环,如果直接在主循环里sleep,会导致摄像头画面卡顿,实时性下降。
  • 重复触发避免:通过last_shown_person变量,确保同一个人连续被识别时不会反复弹窗,只有当新的目标人员被检测到才会触发。
  • 图片路径:确保target_people_images里的图片路径是正确的,相对路径的话要和你的代码脚本在同一目录,或者用绝对路径。

内容的提问来源于stack exchange,提问作者rkoofoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:17:36