Home > Blockchain >  Trying to pad an image with symmetric using np.pad
Trying to pad an image with symmetric using np.pad

Time:08-24

I'm trying to add 5 pixels worth of padding all around the image I have currently. The images are 150x150 pixels and I want to resize them into 160x160 with symmetric padding for my CNN.

Here is the code I am using:

for need_pad_img in os.listdir(old_images_path 'split_images'):   
    if need_pad_img.endswith(".jpg") and not need_pad_img.startswith("."):
        image = Image.open(old_images_path   'split_images/'   need_pad_img)
        data = asarray(image)
        new_data = np.pad(data, pad_width=5, mode='symmetric')
        gen_img = Image.fromarray(new_data).astype(np.uint8).convert('RGB').save(old_images_path   'split_images/'   "pad_"   need_pad_img)

However, I am getting error:


  File "/opt/homebrew/Caskroom/miniforge/base/envs/env_tf/lib/python3.9/site-packages/PIL/Image.py", line 2751, in fromarray
    raise TypeError("Cannot handle this data type: %s, %s" % typekey) from e

TypeError: Cannot handle this data type: (1, 1, 13), |u1

When I run new_data.shape I get (160,160,13) and when I run new_data.dtype I get dtype('uint8').

CodePudding user response:

As an alternative to np.pad, consider allocating an image of the size you want and placing the original in it:

new_data = np.zeros((160, 160, *data.shape[2:]), dtype=np.uint8)
new_data[5:-4, 5:-4, ...] = data

For a more general solution, you could compute 5 and -4 as (new_data.shape[0] - data.shape[0]) // 2 and (data.shape[0] - new_data.shape[0] - 1) // 2, respectively.

  • Related