我有许多不同大小的图像,就像
images = [np.array(shape=(100, 200)), np.array(shape=(150, 100)), np.array(shape=200, 50)...]
是否有任何有效且便捷的方法将零填充到小图像(右下角填充零)并获得大小为(3,200,200)的numpy数组?
答案 0 :(得分: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)
答案 1 :(得分:0)
基于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. ]])