简体   繁体   中英

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. 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.

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.

There is a function in numpy for padding matrices. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM