【发布时间】: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 数组?
【问题讨论】:
我有很多不同尺寸的图片,就像
images = [np.array(shape=(100, 200)), np.array(shape=(150, 100)), np.array(shape=200, 50)...]
是否有任何高效便捷的方法可以将零填充到小图像(在右下角填充零)并获得大小为 (3, 200, 200) 的 numpy 数组?
【问题讨论】:
要向 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 找出解决方法。
基于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. ]])
【讨论】: