[英]How can I zero pad part of a loaded image with Numpy / Keras?
I am loading an image with: 我正在加载图像:
from keras.preprocessing import image
img = image.load_img(image_path, target_size=(224, 224))
x = image.img_to_array(img)
What I want to do is keep the dimension (224 x 224) but pad it. 我要做的是保持尺寸(224 x 224),但要填充它。 Where as normally, I'd have an image like this:
和往常一样,我会有这样的图像:
Instead, I want an image like: 相反,我想要一个像这样的图像:
(black border added for clarification. Not something I actually want) (为清楚起见,添加了黑色边框。这不是我真正想要的东西)
What I want is for the image to be shifted (by some x
and y
) and for the rest to be zeroes. 我想要的是将图像移动(一些
x
和y
),其余部分为零。
The easiest approach is to create an empty matrix and fill the parts you want with the image: 最简单的方法是创建一个空矩阵,然后用图像填充所需的部分:
x=np.ones((224,224,3),dtype=int)*255
x[x_start:,y_start:]=image.img_to_array[x_start:,y_start:]
Notice that you can change the dtype
to uint8
if you need. 请注意,如果需要,可以将
dtype
更改为uint8
。
There is a function in numpy for padding matrices. numpy中有一个用于填充矩阵的函数。 You should specify padding value for each dimension.
您应该为每个尺寸指定填充值。
np.pad(img, ((top_pad, bottom_pad), (left_pad, right_pad), (0, 0)), mode='constant', constant_values=0)
If you need an implementation take a look at this 如果你需要一个实现一起来看看这个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.