我有一个CNN,它的输入是通过Canny边缘检测转换为二值图像的图像,并输出三个类别之一。
img = cv2.imread(path)img = cv2.Canny(img, 33, 76)img = np.resize(img, (26, 26, 1))imgs.append(img)
据我所知,我需要将其转换为3维(26,26,1)的图像,以便网络能够处理。这是我的网络:
IMG_HEIGHT = 26IMG_WIDTH = 26no_Of_Filters=60size_of_Filter=(5,5)size_of_pool=(2,2)no_Of_Nodes = 500model_new = Sequential([ Conv2D(no_Of_Filters, size_of_Filter, padding='same', activation='relu', input_shape=(IMG_HEIGHT, IMG_WIDTH , 1)), MaxPooling2D(pool_size=size_of_pool), Conv2D(no_Of_Filters, size_of_Filter, padding='same', activation='relu'), MaxPooling2D(pool_size=size_of_pool), Conv2D(64, size_of_Filter, padding='same', activation='relu'), MaxPooling2D(pool_size=size_of_pool), Flatten(), Dense(512, activation='relu'), Dense(3, activation='softmax')])
训练过程一切正常。在训练并创建模型后,我想再次用该网络测试图像
test_image = cv2.Canny(test_image ,33,76)test_image = np.resize(test_image, (26, 26, 1))test_image = test_image [np.newaxis, ...]prediction = model.predict(test_image)print(prediction)
现在我得到了以下错误:
ValueError: Error when checking input: expected conv2d_1_input to have 4 dimensions, but got array with shape (26, 26, 1)
为什么训练后的模型现在需要一个4维输入?
回答:
你需要为你的数组增加一个维度,因为错误信息指出,keras
期望一个4D输入。
test_image = test_image[np.newaxis, ...]
keras
处理的形状如(1, 26, 26, 1)
,而不是(26, 26, 1)
。增加的第一个维度是批次大小,keras
需要它。