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

如何在DeepStream Python示例中集成face_recognition库定制开发

解决方案步骤

1. 确认依赖环境

  • 确保face_recognition库已适配Jetson Nano的ARM架构完成安装,优先通过源码编译dlib后再安装face_recognition,避免x86预编译包的兼容问题。
  • 验证DeepStream 6.0的Python绑定正常,原deepstream-imagedata-multistream.py示例可正常运行输出视频流。

2. 添加帧处理的Probe函数

在原示例代码中,选择nvosd元件的sink pad作为帧处理的节点,这里的帧格式稳定且已完成基础OSD处理。添加以下probe函数实现格式转换与人脸识别:

def osd_sink_pad_buffer_probe(pad, info, u_data):
    buf = info.get_buffer()
    if not buf:
        return Gst.PadProbeReturn.OK

    # 获取批量帧元数据
    batch_meta = pyds.gst_buffer_get_nvds_batch_meta(buf)
    l_frame = batch_meta.frame_meta_list
    
    while l_frame is not None:
        try:
            frame_meta = pyds.NvDsFrameMeta.cast(l_frame.data)
        except StopIteration:
            break

        # 提取NV12格式的帧数据
        n_frame = pyds.get_nvds_buf_surface(hash(buf), frame_meta.batch_id)
        # 将NV12转换为face_recognition所需的RGB格式
        frame_bgr = cv2.cvtColor(n_frame, cv2.COLOR_YUV2BGR_NV12)
        frame_rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)

        # 调用face_recognition处理帧
        face_locations = face_recognition.face_locations(frame_rgb)
        face_encodings = face_recognition.face_encodings(frame_rgb, face_locations)

        # 示例:打印当前帧的人脸数量
        print(f"Frame {frame_meta.frame_num}: 识别到 {len(face_locations)} 张人脸")

        # 可选:在帧上绘制人脸框并写回管线
        for (top, right, bottom, left) in face_locations:
            cv2.rectangle(frame_bgr, (left, top), (right, bottom), (0, 255, 0), 2)
        pyds.nvds_buf_surface_set_meta(hash(buf), frame_meta.batch_id, frame_bgr)

        try:
            l_frame = l_frame.next
        except StopIteration:
            break
    return Gst.PadProbeReturn.OK

接着在创建nvosd元件的代码段后,注册该probe:

nvosd = Gst.ElementFactory.make("nvosd", "onscreendisplay")
osdsinkpad = nvosd.get_static_pad("sink")
if not osdsinkpad:
    sys.stderr.write(" 无法获取nvosd的sink pad \n")
osdsinkpad.add_probe(Gst.PadProbeType.BUFFER, osd_sink_pad_buffer_probe, 0)

3. Jetson Nano性能优化

  • 降低输入视频的分辨率与帧率,例如将源视频设为720p/15fps,减少单帧计算量。
  • 设置间隔帧处理,比如每3-5帧执行一次人脸识别,避免管线阻塞:
if frame_meta.frame_num % 5 == 0:  # 每5帧处理一次
    face_locations = face_recognition.face_locations(frame_rgb)
    # 后续识别逻辑

4. 常见问题排查

  • 若出现格式转换错误,确认cv2.cvtColor使用COLOR_YUV2BGR_NV12参数,匹配DeepStream默认的NV12帧格式。
  • 若Python环境报错,检查dlib与face_recognition是否为ARM架构编译版本,可通过pip show dlib查看安装路径与架构信息。
  • 若管线崩溃,查看DeepStream日志输出,确保缓冲处理过程中未出现内存泄漏或格式破坏。

内容的提问来源于stack exchange,提问作者Lăng Khoa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 10:25:16