Search code examples
pythonimagenumpycrop

python - numpy image, crop one side, fill with black the ther


I have a image with resolution 816x624, and would need to make a 640x640 image out of it.

To do so, i'd have to crop the long side (centered), and fill up the short side with black (centered). the resulting image should be the center of the starting image, with a small black strip on top and bottom.

How can this be done?

i tried with:

 crop_img = img1[int(h1 / 2 - 640 / 2):int(h1 / 2 + 640 / 2),
                           int(w1 / 2 - 640 / 2):int(w1 / 2 + 640/ 2)]

but this does not work because h1 i ssmaller than 640.

enter image description here


Solution

  • Given an imput image img, an expected height h and an expected width w:

    def resize_img(img, h, w):
    
      #cut the image
      cutted_img =  img[
          max(0, int(img.shape[0]/2-h/2)):min(img.shape[0], int(img.shape[0]/2+h/2)),
          max(0, int(img.shape[1]/2-w/2)):min(img.shape[1], int(img.shape[1]/2+w/2)),
      ]
    
      #pad the image
      padded_img = np.zeros(shape=(h,w,3), dtype=img.dtype)
      padded_img[
          int(padded_img.shape[0]/2-cutted_img.shape[0]/2):int(padded_img.shape[0]/2+cutted_img.shape[0]/2),
          int(padded_img.shape[1]/2-cutted_img.shape[1]/2):int(padded_img.shape[1]/2+cutted_img.shape[1]/2),
      ] = cutted_img
    
      return padded_img
    

    some exaples:

    url = "https://www.planetware.com/wpimages/2020/02/france-in-pictures-beautiful-places-to-photograph-eiffel-tower.jpg"
    response = requests.get(url)
    start_img = np.array(PIL.Image.open(BytesIO(response.content)))
    plt.imshow(start_img)
    plt.show() #shape = (487, 730, 3)
    

    plt.imshow(resize_img(start_img, 640, 640))
    plt.show() #shape = (640, 640, 3)
    

    I tested on some other pictures:

    shape = (1020, 680, 3)

    shape = (450, 254, 3)

    shape = (847, 564, 3)

    All resized images have size (640, 640, 3) and seem to be properly padded.

    PS. I have used the following libraries:

    import numpy as np
    from matplotlib import pyplot as plt
    import PIL
    import requests
    from io import BytesIO