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

如何解决人脸识别代码中的AttributeError: 'NoneType' object has no attribute 'copy'错误

问题解决:AttributeError: 'NoneType' object has no attribute 'copy'

错误原因

你代码中cv2.imread("reference.jpg.lnk")读取的是Windows快捷方式文件(.lnk后缀),OpenCV无法解析这种文件格式,导致返回None,后续调用copy()方法自然报错。

解决步骤

1. 替换为真实图片路径

  • 删除.lnk后缀,直接使用实际图片文件名,比如图片和代码在同一目录下,改为:
    reference_img = cv2.imread("reference.jpg")
    
  • 如果图片不在代码目录,使用绝对路径,例如:
    reference_img = cv2.imread("C:/Users/HP/Desktop/minor project 2/reference.jpg")
    
    注意路径用正斜杠/或者双反斜杠\\。

2. 添加图片读取校验

在读取图片后增加判断,避免后续代码崩溃:

reference_img = cv2.imread("reference.jpg")
if reference_img is None:
    print("错误:无法读取参考图片,请检查路径是否正确")
    exit()
img = reference_img.copy()

3. 修正代码其他小问题

  • cv2.waitkey改为cv2.waitKey(K大写),否则会找不到该函数。
  • cv2.putText参数格式错误,文本和坐标要分开,比如:
    cv2.putText(frame, "AUTHORIZED", (20,450), cv2.FONT_HERSHEY_SIMPLEX, 2, (0,255,0), 5)
    
  • cv2.destroyAllWindows()移到循环外面,否则会导致窗口频繁销毁重建。

修正后的完整代码

import cv2
import threading
from deepface import DeepFace

cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

counter = 0
face_match = False

# 读取参考图片,修正路径并添加校验
reference_img = cv2.imread("reference.jpg")
if reference_img is None:
    print("错误:无法读取参考图片,请检查路径是否正确")
    exit()
img = reference_img.copy()

def check_face(frame):
    global face_match
    try:
        if DeepFace.verify(frame, img)['verified']:
            face_match = True
        else:
            face_match = False
    except ValueError:
        face_match = False

while True:
    ret, frame = cap.read()
    if not ret:
        print("无法读取摄像头画面")
        break
    
    if counter % 30 == 0:
        try:
            threading.Thread(target=check_face, args=(frame.copy(),)).start()
        except Exception as e:
            print(f"线程启动失败:{e}")
    
    counter += 1

    # 修正putText参数格式
    if face_match:
        cv2.putText(frame, "AUTHORIZED", (20, 450), cv2.FONT_HERSHEY_SIMPLEX, 2, (0,255,0), 5)
    else:
        cv2.putText(frame, "UNAUTHORIZED", (20, 450), cv2.FONT_HERSHEY_SIMPLEX, 2, (0,0,255), 5)

    cv2.imshow("Face Authentication Cam", frame)

    # 修正waitKey的大小写
    key = cv2.waitKey(1)
    if key == ord("q"):
        break

# 释放资源并销毁窗口
cap.release()
cv2.destroyAllWindows()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 14:41:17