首页 > 解决方案 > 如何使用 keras 预测来自 OpenCV 的 VideoCapture 的预训练模型?

问题描述

我的代码是

model = ResNet50(weights='imagenet')

def read_cam(video_capture):
    if video_capture.isOpened():
        windowName = "yolo"
        cv2.namedWindow(windowName, cv2.WINDOW_NORMAL)
        cv2.resizeWindow(windowName, 1280, 720)
        cv2.moveWindow(windowName, 0, 0)
        cv2.setWindowTitle(windowName, "Yolo Object Detection")
        while True:
            # Check to see if the user closed the window
            if cv2.getWindowProperty(windowName, 0) < 0:
                break

            ret_val, frame = video_capture.read()
            print(frame)
            frame = np.expand_dims(frame, axis=0)
            frame = preprocess_input(frame)

            preds = model.predict(frame)
            # print(preds)
            print('Predicted:', decode_predictions(preds, top=3)[0])

但是,这会导致一些错误。首先,显然,它需要一个不同大小的数组:

ValueError: Error when checking input: expected input_1 to have shape (224, 224, 3) but got array with shape (720, 1280, 3)

标签: pythonopencvkerasresnet

解决方案


使用 cv2. resize 函数在调用 model.predict 之前更改框架,因为您使用的预训练模型只接受大小为 224x224 的图像。

 frame=cv2.resize(frame,(224,224))

推荐阅读