IndexError:使用np.argmax函数时,列表索引超出范围

时间:2019-07-15 04:27:35

标签: tensorflow machine-learning keras deep-learning computer-vision

我正在处理CNN-LSTM的动作识别问题,并将所有帧转换为CSV文件。我训练了模型并以h5格式保存了模型。训练后,当我使用Open CV在视频文件上进行测试时,会引发错误。下面是我的代码:-

import cv2
import numpy as np
from keras.models import load_model



model = load_model("C:/Users/Sonu/Desktop/important/model.h5")

model.summary()
classes = ['goal', 'free', 'credit']
cap = cv2.VideoCapture("C:/Users/Sonu/Desktop/important/out1.mp4")

while cap.isOpened():
    _, frame = cap.read()

    frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

    resized = cv2.resize(frame, (51250, 50), interpolation = cv2.INTER_CUBIC)
    frame = resized.reshape(1, 1025, 50, 50, 3)

    pred_array = model.predict(frame)
    print(pred_array)

    result = classes[np.argmax(pred_array)]
    #result = classes[pred_array][0]

    score = float("%0.2f" % (max(pred_array[0]) * 100))
    #score = float("{.2f}".format((classes) * 100))
    print(f'Result: {result}, Score: {score}')

    cv2.imshow("frame", frame)


    if cv2.waitKey(25) & 0xFF == ord('q'):
        break

cv2.destroyAllWindows()
cap.release()

错误日志如下:-

File "C:/Users/Sonu/Desktop/important/detecting_video_lrcnn.py", line 32, in <module>
    result = classes[np.argmax(pred_array)]


IndexError: list index out of range

有人可以指导我我做错了什么吗?在此先感谢大家。

1 个答案:

答案 0 :(得分:0)

如果不运行代码,我相信您的问题出在pred_array = model.predict(frame)行上。公平地假设pred_array的长度大于3,即class数组的长度。因此,如果pred_array大于长度3,并且最大元素的位置大于该长度,则result = classes[np.argmax(pred_array)]将导致您收到的IndexError错误消息。

希望这有助于弄清问题所在!