【问题标题】:Pad dynamic sizes of images填充图像的动态大小
【发布时间】:2018-12-18 17:58:37
【问题描述】:

我有很多不同尺寸的图片,就像 images = [np.array(shape=(100, 200)), np.array(shape=(150, 100)), np.array(shape=200, 50)...]

是否有任何高效便捷的方法可以将零填充到小图像(在右下角填充零)并获得大小为 (3, 200, 200) 的 numpy 数组?

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    要向 Numpy 数组添加填充,您可以使用以下命令:

    中心内边距:

    shape = (200,200)
    padded_images = [np.pad(a, np.subtract(shape, a.shape), 'constant', constant_values=0) for a in images]
    

    右下边距:

    def pad(a):
        """Return bottom right padding."""
        zeros = np.zeros((200,200))
        zeros[:a.shape[0], :a.shape[1]] = a
        return zeros
    
    vectorized_pad = np.vectorize(pad)
    padded_images = vectorized_pad(images)
    

    【讨论】:

    • 简洁有效
    • 你为什么从另一个问题中删除你的答案?我尝试了代码,它返回了一个白色图像。尝试使用np.apply_along_axis 找出解决方法。
    • 我删除了答案,因为我相信其他答案更符合 OP 的要求。你的回答没有用吗?
    • 我的回答成功了。但是解决问题的方法有很多不是吗?
    • 如果您认为它可能对其他用户有用,我将恢复答案。
    【解决方案2】:

    基于this solution,您可以执行以下操作以在图像的右侧和底部填充零:

    shape=(200,200)
    
    new_images = [np.zeros(shape) for _ in range(len(images))]
    
    for i,image in enumerate(images):
        new_images[i][:image.shape[0], :image.shape[1]] = image
    

    示例:

    举个简单的例子,填充一组小图像以塑造(5,5):

    # Create random small images
    images=[np.random.randn(2,3), np.random.randn(3,3), np.random.randn(5,5)]
    
    # Print out the shape of each image just to demonstrate
    >>> [image.shape for image in images]
    [(2, 3), (3, 3), (5, 5)]
    # Print out first image just to demonstrate
    >>> images[0]
    array([[-0.49739434,  1.06979644, -0.52647292],
           [ 1.21681931, -0.96205689,  0.050574  ]])
    
    # Set your desired shape
    shape=(5,5)
    
    # Create array of zeros of your desired shape
    new_images = [np.zeros(shape) for _ in range(len(images))]
    
    # loop through and put in your original image values in the beginning
    for i,image in enumerate(images):
        new_images[i][:image.shape[0], :image.shape[1]] = image
    
    # print out new image shapes to demonstrate
    >>> [image.shape for image in new_images]
    [(5, 5), (5, 5), (5, 5)]
    # print out first image of new_images to demonstrate:
    >>> new_images[0]
    array([[-0.49739434,  1.06979644, -0.52647292,  0.        ,  0.        ],
           [ 1.21681931, -0.96205689,  0.050574  ,  0.        ,  0.        ],
           [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
           [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ],
           [ 0.        ,  0.        ,  0.        ,  0.        ,  0.        ]])
    

    【讨论】:

      猜你喜欢
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      • 2012-05-14
      • 2011-09-15
      • 1970-01-01
      • 1970-01-01
      • 2021-01-17
      • 1970-01-01
      相关资源
      最近更新 更多