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

如何在运行时加载新增图片适配OpenCV人脸识别系统?

运行时动态加载新增人脸图片的解决方案

1. 记录已处理图片的元数据

  • 维护一个集合存储已处理的图片路径,同时关联对应的人脸编码与标签(可直接用图片文件名作为标签)。
  • 将记录持久化到本地文件,避免程序重启后丢失已处理信息:
import json
import os

# 初始化已处理图片集合
processed_images = set()
# 存储记录的本地文件路径
RECORD_FILE = "processed_images.json"

# 加载历史处理记录
if os.path.exists(RECORD_FILE):
    with open(RECORD_FILE, 'r') as f:
        processed_images = set(json.load(f))

# 保存当前处理记录到本地
def save_processed_records():
    with open(RECORD_FILE, 'w') as f:
        json.dump(list(processed_images), f)

2. 定时扫描文件夹处理新增图片

  • 启动后台定时线程,定期扫描目标人脸图片文件夹,筛选出未处理的新增图片。
  • 对新增图片执行人脸编码,并线程安全地更新全局人脸编码库:
import threading
import face_recognition
import time

# 人脸图片文件夹路径
FACE_IMG_DIR = "your_face_images_directory"
# 全局存储已知人脸编码与对应名称
known_face_encodings = []
known_face_names = []
# 线程锁,保证多线程访问数据的安全性
lock = threading.Lock()

def scan_and_process_new_images():
    global known_face_encodings, known_face_names
    # 遍历文件夹内所有文件
    for img_name in os.listdir(FACE_IMG_DIR):
        img_path = os.path.join(FACE_IMG_DIR, img_name)
        # 跳过非图片文件与已处理文件
        if not img_path.lower().endswith(('.png', '.jpg', '.jpeg')) or img_path in processed_images:
            continue
        # 尝试加载图片并提取人脸编码
        try:
            img = face_recognition.load_image_file(img_path)
            face_encodings = face_recognition.face_encodings(img)
            # 仅处理包含人脸的图片
            if face_encodings:
                with lock:
                    known_face_encodings.append(face_encodings[0])
                    # 提取文件名作为人脸标签(可根据需求自定义)
                    known_face_names.append(os.path.splitext(img_name)[0])
                # 标记为已处理并保存记录
                processed_images.add(img_path)
                save_processed_records()
                print(f"已加载新增人脸:{img_name}")
        except Exception as e:
            print(f"处理图片{img_name}失败:{str(e)}")
    # 每隔5秒执行一次扫描(可根据需求调整间隔)
    threading.Timer(5.0, scan_and_process_new_images).start()

# 启动定时扫描线程
scan_and_process_new_images()

3. 保证实时识别的线程安全

  • 在摄像头实时识别的主循环中,访问全局人脸编码库时必须加锁,避免后台更新线程引发数据不一致:
import cv2

video_capture = cv2.VideoCapture(0)

while True:
    ret, frame = video_capture.read()
    if not ret:
        break
    # 转换为face_recognition要求的RGB格式
    rgb_frame = frame[:, :, ::-1]
    # 检测画面中的人脸位置与编码
    face_locations = face_recognition.face_locations(rgb_frame)
    face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
    
    face_names = []
    with lock:
        # 使用最新的人脸编码库进行匹配
        for face_encoding in face_encodings:
            matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
            name = "Unknown"
            if True in matches:
                first_match_index = matches.index(True)
                name = known_face_names[first_match_index]
            face_names.append(name)
    
    # 在画面上绘制识别结果(示例代码)
    for (top, right, bottom, left), name in zip(face_locations, face_names):
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
    
    cv2.imshow('Video', frame)
    # 按q退出程序
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

video_capture.release()
cv2.destroyAllWindows()

优化建议

  • 可根据文件修改时间筛选待处理图片,只扫描最近更新的文件,减少不必要的计算开销。
  • 增加图片完整性校验,跳过损坏或无法读取的图片,避免扫描流程中断。
  • 若人脸图片数量较大,可改用SQLite数据库存储已处理记录与人脸编码,提升查询与更新效率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 17:15:11