首页 > 解决方案 > ValueError:检查输入时出错:预期 input_1 的形状为 (1, 28, 28) 但得到的数组的形状为 (28, 28, 1)

问题描述

import cv2
from PIL import ImageGrab, Image
import numpy as np
import h5py

import os
import pandas as pd
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Dense, Activation,Dropout,Conv2D, MaxPooling2D,BatchNormalization
from tensorflow.keras.optimizers import Adam, Adamax
from tensorflow.keras.metrics import categorical_crossentropy
from tensorflow.keras import regularizers
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Model, load_model, Sequential

word_dict = {0:'0',1:'1',2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',9:'9',10:'A',11:'B',12:'a',13:'b'}

model = load_model('small_letter_model.h5')

# Prediction on external image...

img = cv2.imread(r'C:/Users/Swaraj/Desktop/img_3.jpg')
img_copy = img.copy()

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = cv2.resize(img, (224, 224))

img_copy = cv2.GaussianBlur(img_copy, (21,21), 0)
#detector.avg = img_copy.astype(float)
img_gray = cv2.cvtColor(img_copy, cv2.COLOR_BGR2GRAY)
img_thresh = cv2.threshold(img_gray, 100, 255, cv2.THRESH_BINARY_INV)

img_final = cv2.resize(img, (28,28))
#img_final =np.reshape(img, (0,0,0,0))

#img_final = np.array(img)
img_final = img_final.reshape(1,28,28,1)

img_pred = word_dict[np.argmax(model.predict(img_final))]

cv2.putText(img, "", (20,25), cv2.FONT_HERSHEY_TRIPLEX, 0.7, color = (0,0,230))
cv2.putText(img, "Prediction: " + img_pred, (20,410), cv2.FONT_HERSHEY_DUPLEX, 1.3, color =  (255,0,30))
cv2.imshow('Handwritten Math Symbol Recognition _ _ _ ', img)


while (1):
    k = cv2.waitKey(1) & 0xFF
    if k == 27:
        break
cv2.destroyAllWindows()

我收到错误为“ValueError:检查输入时出错:预期 input_1 具有形状(1、28、28)但得到形状为(28、28、1)的数组”,同时识别图像,同时创建模型给出输入形状是input_shape=(128,128,3) 代码为 base_model=tf.keras.applications.MobileNetV2( include_top=False, input_shape=(128,128,3), pooling='max', weights='imagenet') 生成器如何接收一个( 1,28,28) 数组?任何帮助表示赞赏!请给建议提前谢谢

标签: python-3.xtensorflowmachine-learningkerasocr

解决方案


推荐阅读