【问题标题】:How to add batch to a image using Tensorflow/numpy/keras?如何使用 Tensorflow/numpy/keras 向图像添加批处理?
【发布时间】:2019-12-15 02:42:35
【问题描述】:

我有一个形状 (128,64,3) 的图像。现在我需要向该图像添加批次以适合模型。我的图像的输出应该是 (1,128,64,3) 其中 1 是 batch_size 而不会影响图像特征。

【问题讨论】:

    标签: image numpy tensorflow keras cv2


    【解决方案1】:

    为了在模型中输入图像,您必须扩大其尺寸。你可以这样做:

    image = np.random.rand(128, 64, 3)
    # Image shape (128, 64, 3)
    image = tf.expand_dims(image, axis=0)
    # Image shape (1, 128, 64, 3)
    

    但是,如果要绘制图像,它必须具有 3D 形状。换句话说,初始形状很好。但是,如果您已经有一批形状为(1, 128, 64, 3) 的图像,那么您可以像这样挤压它们的形状:

    img = np.squeeze(image)
    # Image shape (128, 64, 3)
    matplotlib.pyplot.imshow(img)
    

    像这样,绘制图像应该是可行的。因此,总而言之,模型期望的图像输入与您想要绘制图像所需的图像输入不同。也就是说,模型需要 4D 输入 (batch_size, width, height, channels),而 matplotlib 需要 3D 输入 (width, height, channels)。

    【讨论】:

    • img = np.expand_dims(img, axis=0) #试过这个,但在尝试使用matplotlib.pyplot.imshow(img) 时出现此错误。 TypeError:图像数据的尺寸无效
    • 如果你想在图定义之外进行张量展开,那很好。我假设您想在图表中执行此操作。
    • 我建立了一个模型,但这个图像不符合这个模型。为了使图像适合模型,我需要将其形状变成(1,128,64,3)
    • 即使tf.expand_dims(image,axis=0) 在绘图时也会抛出同样的错误。
    • 挤压后又回到(128,64,3)
    猜你喜欢
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多