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

首次使用Dlib遇退出码-1073741819(0xC0000005),求解决方法

Dlib运行报错0xC0000005的解决办法

错误码-1073741819 (0xC0000005)本质是内存访问违规,针对你的代码场景,可按以下步骤排查解决:

1. 验证模型文件的正确性

Dlib的形状预测器和人脸识别模型文件是关键,路径错误或文件损坏会直接触发该错误:

  • 确认shape_predictor_68_face_landmarks.dat和dlib_face_recognition_resnet_model_v1.dat与代码脚本在同一目录,或使用绝对路径指定文件位置,例如:
    sp = dlib.shape_predictor("C:/projects/face_rec/shape_predictor_68_face_landmarks.dat")
    
  • 检查文件完整性:两个模型文件大小分别约99MB和100MB,若文件过小,说明下载过程中断,重新下载即可。

2. 修复图像读取逻辑

代码中直接拼接路径+文件名容易出错,且未处理损坏图片的情况:

  • 改用os.path.join拼接路径,避免斜杠缺失问题;添加图片读取有效性判断:
    img_path = os.path.join(path, fn)
    img = cv2.imread(img_path)
    if img is None:
        print(f"跳过损坏/无法读取的图片: {fn}")
        continue
    img = img[:, :, ::-1]  # BGR转RGB
    

3. 调整Dlib检测参数

过高的检测精度可能导致内存溢出:

  • 将人脸检测器的上采样次数从1改为0(减少内存占用):
    dets = detector(img, 0)
    
  • 若仍报错,可将人脸特征计算的num_jitters参数从1改为0:
    face_desc = model.compute_face_descriptor(img, shape, 0)
    

4. 确保版本兼容性

Python与Dlib版本不匹配也会引发内存错误:

  • 卸载现有Dlib后重装,优先选择适配当前Python版本的预编译包:
    pip uninstall dlib -y
    pip install dlib
    
  • 若Windows系统编译安装失败,可尝试安装对应Python版本的预编译wheel包(无需自行编译)。

5. 优化内存占用

若处理大量高清图片,内存过载也会触发该错误:

  • 每次处理完单张图片后,手动回收内存:
    import gc
    gc.collect()
    
  • 避免一次性将所有特征存入列表,可分批写入文件,减少内存占用。

修改后的完整代码示例

import numpy as np, cv2, dlib, os, pickle, gc

path = './facedata/'
detector = dlib.get_frontal_face_detector()
# 使用绝对路径或确认文件在当前目录
sp = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
model = dlib.face_recognition_model_v1('dlib_face_recognition_resnet_model_v1.dat')
FACE_DESC = []
FACE_NAME = []

for fn in os.listdir(path):
    if fn.endswith('.jpg'):
        img_path = os.path.join(path, fn)
        img = cv2.imread(img_path)
        if img is None:
            print(f"跳过无效图片: {fn}")
            continue
        img = img[:, :, ::-1]  # BGR转RGB
        dets = detector(img, 0)
        for k, d in enumerate(dets):
            shape = sp(img, d)
            face_desc = model.compute_face_descriptor(img, shape, 1)
            FACE_DESC.append(face_desc)
            print('loading...', fn)
            FACE_NAME.append(fn[:fn.index('_')])
        gc.collect()  # 回收内存

pickle.dump((FACE_DESC, FACE_NAME), open('trainset.pk', 'wb'))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 20:26:16