keras ValueError:无法将大小为200704的数组整形为shape(1,224,224,3)

vdzxcuhz  于 2023-04-21  发布在  其他
关注(0)|答案(1)|浏览(237)

所以我们想用picamera2来运行我们的程序。我该如何解决这个问题?:代码如下:

import numpy as np
import time
import tensorflow as tf
from keras.models import load_model
from keras.preprocessing import image

import cv2
from picamera2 import Picamera2

cv2.startWindowThread()

picam2 = Picamera2()
picam2.configure(picam2.create_preview_configuration(main={"format": 'XRGB8888', "size": (640,480)}))
picam2.start()

#Disable scientific notation for clarity
np.set_printoptions(suppress=True)

#Load the model
model = load_model("keras_model.h5", compile=False)

#Load the labels
class_names = open("labels.txt", "r").readlines()

while True:
    im = picam2.capture_array()
    
    im = cv2.resize(im, (224, 224), cv2.INTER_NEAREST)

    grey = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

    cv2.imshow("Camera", grey)
    
#---Make the image a numpy array and reshape it to the models input shape.---
    im = np.asarray(im, dtype=np.float32).reshape(1, 224, 224, 3)

#---Normalize the image array------------------------------------------------
    im = (im / 127.5) - 1

#---Predicts the model-------------------------------------------------------
    prediction = model.predict(image)
    index = np.argmax(prediction)
    class_name = class_names[index]
    confidence_score = prediction[0][index]
    
    print("Class:", class_name[2:], end="")
    print("Confidence Score:", str(np.round(confidence_score * 100))[:-2], "%")

错误如下:

im = np.asarray(im,dtype=np.float32).reshape(1,224,224,3)ValueError:无法将大小为200704的数组重新整形为形状(1,224,224,3)
我试图改变整形函数的输入。我希望picamera2能顺利运行,但结果是它不能接受形状数组的大小。代码在正常的网络摄像头上工作,除了picamera2

vc9ivgsu

vc9ivgsu1#

您使用的是XRGB8888,它有4个通道。这意味着形状应该是(1,224,224,4),这相当于您要重塑的数组的形状,1 * 244 * 244 * 4 = 200704
尝试:

im = np.asarray(im, dtype=np.float32).reshape(1, 224, 224, 4)

相关问题