属性错误:模块'keras.preprocessing.image'没有属性'img_to_array'

3lxsmp7m  于 2022-11-13  发布在  其他
关注(0)|答案(1)|浏览(262)

我正在尝试运行一个来自面部表情讲述者的github的代码,但我得到了一个属性错误,

错误为:

line 27, in <module>
    img_pixel = image.img_to_array(roi_gray)
AttributeError: module 'keras.preprocessing.image' has no attribute 'img_to_array'

完整内容如下:

import os
import cv2
import numpy as np
from keras.models import model_from_json
from 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+w, x:x+h]
        roi_gray = cv2.resize(roi_gray, (48, 48))
        img_pixel = image.img_to_array(roi_gray)
        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

当我运行代码,相机打开了一秒钟,然后这个错误显示出来,请帮助我解决这个错误
我试图使用其他stackoverflow问题来更改keras库的导入,类似于我的错误,但我没有得到任何解决方案

klh5stk1

klh5stk11#

图像是deprecated
您可以使用

from tensorflow.keras.utils import img_to_array

...

img_pixel = img_to_array(roi_gray)

相关问题