繁体   English   中英

如何将输入图像数组从 1d 重塑为 3d

[英]how to reshape input image array from 1d to 3d

我已经构建了如下的图像分类器:

import tensorflow as tf
from tensorflow.keras.applications.mobilenet import preprocess_input

image_width, image_height = 224, 224
input_shape = (image_width, image_height, 3)
self.model = tf.keras.Sequential()
        pretrained_layer = tf.keras.applications.mobilenet.MobileNet(
            weights="imagenet", include_top=False, input_shape=self.input_shape
        )
self.model.add(pretrained_layer)
self.model.add(tf.keras.layers.GlobalAveragePooling2D())
self.model.add(tf.keras.layers.Dense(256, activation="relu"))
self.model.add(tf.keras.layers.Dropout(0.5))
self.model.add(tf.keras.layers.Dense(128, activation="relu"))
self.model.add(tf.keras.layers.Dropout(0.2))
self.model.add(tf.keras.layers.Dense(len(DATA_LABELS), activation="sigmoid"))

self.model.compile(
            optimizer=tf.keras.optimizers.Adam(0.0005),
            loss="binary_crossentropy",
            metrics=["accuracy"],
        )

我还有一个预测函数,它期望输入为 numpy 数组

def predict(self, image):
    """Predict the labels for a single screenshot
       image -- The numpy array of the image to classify
    """
    img = np.expand_dims(image, axis=0)
    img = preprocess_input(img)

    prediction = self.model.predict(img, batch_size=1)

现在我得到一个图像,它是 1d numpy 数组 (23280,),当我将它提供给预测模型时,我得到如下错误:

prediction = model.predict(np.asarray(bytearray(ss_read)))  # np.asarray(bytearray(ss_read)) is 1d numpy array (23280,)
ValueError: Error when checking input: expected mobilenet_1.00_224_input to have 4 dimensions, but got array with shape (1, 23280)

那么,如何重塑这个 numpy 数组并使其为预测器做好准备? 我想我可以做一些类似np.reshape(np.asarray(bytearray(ss_read)), (image_width, image_height, 3)) ,但是在这种情况下(224 * 224 * 3 = 150528 > 23280)。 我应该做这样的事情来代替np.reshape(np.asarray(bytearray(ss_read)), (image_width, -1, 3))吗?

假设您的图像是 3D,您会得到width * height = 23280/3 = 7760

因此,您只有一些宽高对的可能性,即:

[(95, 82), (190, 41), (205, 38), (410, 19), (779, 10), (1558, 5), (3895, 2)]
[(82, 95), (41, 190), (38, 205), (19, 410), (10, 779), (5, 1558), (2, 3895)]

其中没有一个是224 x 224

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM