如何使用Numpy / Keras对填充的图像的部分进行零填充?

时间:2019-04-19 15:06:30

标签: python numpy keras

我正在使用以下图片加载图片:

from keras.preprocessing import image
img = image.load_img(image_path, target_size=(224, 224))
x = image.img_to_array(img)

我想做的是保持尺寸(224 x 224),但要填充它。和往常一样,我会有这样的图像:

enter image description here

相反,我想要一张像这样的图像:

enter image description here

(为清楚起见添加了黑色边框。我实际上并不是想要的东西)

我想要的是使图像移动(分别移动一些xy),并使其余部分为零。

2 个答案:

答案 0 :(得分:1)

最简单的方法是创建一个空矩阵,并用图像填充所需的部分:

x=np.ones((224,224,3),dtype=int)*255
x[x_start:,y_start:]=image.img_to_array[x_start:,y_start:]

请注意,您可以根据需要将dtype更改为uint8

答案 1 :(得分:1)

在numpy中有一个用于填充矩阵的函数。您应该为每个尺寸指定填充值。

np.pad(img, ((top_pad, bottom_pad), (left_pad, right_pad), (0, 0)), mode='constant', constant_values=0)

如果您需要实现,请查看this