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

运行GitHub面部情绪识别代码遇AttributeError:img_to_array缺失

解决Keras中image.img_to_array不存在的AttributeError问题

这个错误的核心原因是Keras版本迭代后,img_to_array函数的位置发生了变更:旧版Keras中该函数位于keras.preprocessing.image,但新版(尤其是TensorFlow集成的Keras)已经将其迁移到tf.keras.preprocessing.image路径下;另外,由于你的输入roi_gray本身就是numpy数组,也可以直接用numpy替代该函数的功能,避免依赖Keras的API变更。

以下是两种可行的解决方法:

方法1:修正导入路径

将原代码中的导入语句:

from keras.preprocessing import image

替换为:

from tensorflow.keras.preprocessing import image

该方法适用于使用TensorFlow作为后端的Keras环境,是最直接的版本适配方案。

方法2:用Numpy替代img_to_array

由于roi_gray已经是OpenCV处理后的灰度图numpy数组,无需调用Keras的函数转换,直接扩展维度即可满足模型输入要求:
将原代码中的:

img_pixel = image.img_to_array(roi_gray)

替换为:

img_pixel = np.expand_dims(roi_gray, axis=-1)

此方法不依赖Keras的API,兼容性更强,还能减少不必要的函数调用。

额外修复:窗口关闭函数的语法错误

原代码最后一行cv2.destroyAllWindows缺少括号,会导致程序结束后窗口无法正常关闭,需修改为:

cv2.destroyAllWindows()

修改后的完整代码

import os
import cv2
import numpy as np
from tensorflow.keras.models import model_from_json
from tensorflow.keras.preprocessing import image

model = model_from_json(open("fer.json", "r").read())
model.load_weights('fer.h5')


face_haar_cascade = cv2.CascadeClassifier(
    'haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)

while True:
    ret, test_img = cap.read()
    if not ret:
        continue
    gray_img = cv2.cvtColor(test_img, cv2.COLOR_BGR2GRAY)

    faces_detect = face_haar_cascade.detectMultiScale(gray_img, 1.32, 5)

    for (x, y, w, h) in faces_detect:
        cv2.rectangle(test_img, (x, y), (x+w, y+h), (255, 0, 0), thickness=7)
        roi_gray = gray_img[y:y+h, x:x+w]  # 修复原代码笔误:y:y+w改为y:y+h,确保ROI截取正确
        roi_gray = cv2.resize(roi_gray, (48, 48))
        img_pixel = np.expand_dims(roi_gray, axis=-1)
        img_pixel = np.expand_dims(img_pixel, axis=0)
        img_pixel /= 255
        predictions = model.predict(img_pixel)
        max_index = np.argmax(predictions[0])
        emotions = ('angry', 'disgust', 'fear', 'happy',
                    'sad', 'surprise', 'neutral')
        predicted_emotion = emotions[max_index]
        cv2.putText(test_img, predicted_emotion, (int(x), int(y)),
                    cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)

    resize_img = cv2.resize(test_img, (1000, 700))
    cv2.imshow('Facial emotion analysis ', resize_img)

    if cv2.waitKey(10) == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 00:25:32