这个问题已经困扰我很长时间了,我一直找不到解决方案。
问题: 我需要对训练的人工智能进行“重塑”练习,但我无法做到。
通常,当你从外部获取相同的图片时,它是有效的。
def load_image(filename): img = load_img(filename, grayscale=True, target_size=(28, 28)) img = img_to_array(img) img = img.reshape(1, 28, 28, 1) img = img.astype('float32') img = img / 255.0 return img def run_example(): img = load_image('images/5.png') model = load_model('final_model.h5') digit = model.predict_classes(img) print(digit[0]) run_example()
这段代码是有效的,但当我想从一张有很多数字的图片中获取数字时,我必须从图片内部获取这些数字。我能够在这里获取一个数字,其中一个是这样的:
digits_with_zeros[0].shape# output: (171, 171)
当我尝试对这个序列应用“重塑”时,我得到了这样的错误。
img = digits_with_zeros[0].reshape(28,28)img = img_to_array(img)img = img.reshape(1, 28, 28, 1)img = img.astype('float32')img = img / 255.0model = load_model('final_model.h5')digit = model.predict_classes(img)
输出:
----> 1 img = digits_with_zeros[0].reshape(-1,28,28,1) 2 img = img_to_array(img) 3 img = img.reshape(1, 28, 28, 1) 4 img = img.astype('float32') 5 img = img / 255.0ValueError: cannot reshape array of size 29241 into shape (28,28,1)
回答:
img = digits_with_zeros[0]img = cv2.resize(img, dsize=(28, 28))img = np.array(img).reshape(-1, 28,28,1)model = load_model('final_model.h5')digit = model.predict_classes(img)