【问题标题】:numpy: fastest way to change image shape from 224 x 224 x 3 to 3 x 224 x 224numpy:将图像形状从 224 x 224 x 3 更改为 3 x 224 x 224 的最快方法
【发布时间】:2017-12-30 17:56:01
【问题描述】:

我将使用 Keras 预训练的 Inception V3 模型。预处理后的图像形状为 224 x 224 x 3。但 Keras Inception V3 模型的输入是 (?, 3 , ?, ?),即在批量大小之后进入通道。所以我做了数组重塑。但这使整个事情变得超级慢并且占用了内存,我不知道为什么。

注意:当图像形状为 224、224、3 时,它在简单的 CNN 上运行良好。但是输入简单的 CNN 的 3、224、224 会使事情变得超级慢并且内存溢出。

这是我的代码:

def get_image_preprocessed(image_name):
    im = Image.open(image_name)
    im = np.asarray(im)
    im = im/float(255)
    im = im.reshape(3,224,224) #this changes 224,224,3 to 3,224,224
    return im

这是输入张量形状

tf.Tensor 'input_1:0' shape=(?, 3, ?, ?) dtype=float32

更多信息:

型号-

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(3,224, 224), padding='same', activation='relu', kernel_constraint=maxnorm(3)))
model.add(Dropout(0.2))
model.add(Conv2D(32, (3, 3), activation='relu', padding='same', kernel_constraint=maxnorm(3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(512, activation='relu', kernel_constraint=maxnorm(3)))
model.add(Dropout(0.5))
model.add(Dense(3, activation='softmax'))

生成器函数-

def generator(save_dir_path, encoding_list, batch_size, image_size):
    # Create empty arrays to contain batch of features and labels#
    batch_features = np.zeros((batch_size, 3, image_size, image_size))
    batch_labels = np.zeros((batch_size,len(encoding_list)))
    image_list= [file for file in os.listdir(save_dir_path) if (file.endswith('.jpeg') or file.endswith('.-'))]
    while True:
        for i in range(batch_size):
            # choose random index in features
            image_name= random.choice(image_list)
            batch_features[i] = get_image_preprocessed(save_dir_path, image_name)
            batch_labels[i] = np.asarray(get_encoding(encoding_list, image_name.split('_')[0]))
        yield batch_features, batch_labels

【问题讨论】:

  • 这看起来像是transpose 问题,而不是reshape 问题。 3 应继续表示通道,224,224 应继续表示图像形状。
  • 我做了,问题没有解决。我在这里添加了更多信息。
  • 问题出在后端。您需要阅读文档以正确使用此模型。

标签: python numpy keras


【解决方案1】:

您可以为此使用.transpose

im = im.transpose(2,0,1)

所以从现在开始,旧的第三索引(2)是第一索引,旧的第一索引(0)是第二索引,旧的第二索引(1)是第三索引.

因此,如果您访问 im[i,j,k] 就像您在转置之前访问了 im[j,k,i]

【讨论】:

  • 我只是做了转置,问题仍然存在。使用 224,224,3 时大约需要 300MB,但使用 3,224,224 时需要 4.4GB。这太疯狂了。
  • @sjishan:这几乎是不可能的,因为transpose创建了一个新数组,它创建了一个视图。通常这需要大约 100 个字节。
  • 嗨,是的。我想通了,这不是transposereshape 的问题。 224,224,3 创建了 1,910,851 个参数。 3,224,224 创建 205,533,091 个参数。这就是内存溢出。
【解决方案2】:

除了reshapetranspose,还有一个类似的解决方案:Numpy 库中的swapaxes。以下行将数组im 中的第一个轴与第三个轴交换。

im.swapaxes(0,2)

如果 a 是 ndarray,则返回 a 的视图;否则一个新的 数组被创建。 --引用自numpy-1.13.0 Docs

参考

How does numpy.swapaxes work?

【讨论】:

    猜你喜欢
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    • 2021-02-24
    • 1970-01-01
    相关资源
    最近更新 更多